본문 바로가기

Java/기본

[Java] IO스트림 사용하기 - 스트림 연결하기(Stream chaining)

스트림 연결이란

  • 입력스트림+ 입력스트림+ 입력스트림
  • 출력스트림+ 출력스트림+ 출력스트림

이런 식으로 스트림을 연결하는 것을 말한다. 수행기능 향상이 목적이다.

 

버퍼란

버퍼(buffer)는 데이터를 전송시키기 전에 데이터가 일시적으로 보관하는 메모리 영역이다. 버퍼링(buffering)은 버퍼를 채우는 활동을 의미하는데, 버퍼를 사용하면 스트림을 서로 연결해 입출력 수행능력을 향상시킬 수 있다. 

 

버퍼를 사용하면 수행능력이 향상되는 이유

버퍼를 사용하면 '논리적' 데이터 덩어리를 모아서 하나의 '물리적' 연산으로 처리한다.

  • 버퍼를 사용하지 않는 경우
    • 프로그램이 read, write 호출
    • 호출할 때마다 데이터 read, write 수행
    • 수행 횟수 많음
  • 버퍼를 사용하는 경우
    • 프로그램이 read, write 호출 -> 데이터가 buffer애 쌓임
    • buffer 가 꽉차면 그제서야 데이터를 read, write 수행
    • 실제 수행 횟수 적음

 

 

 

입력 스트림 연결

입력 수행 능력향상을 위해 BufferedInputStream을 사용할 수 있다

 

 

아래 코드를 보자.

InputStream과 BufferedInputStream을 연결했다

public static void main(String[] args) {
	InputStream inputStream = null;
	BufferedInputStream bufferedIS = null;
	try {
		String fileName = "D:/Programming/_temp/test11.txt";
		inputStream = new FileInputStream(fileName);
		bufferedIS = new BufferedInputStream(inputStream);
		int a ;
		while(( a = bufferedIS.read()) != -1 ){
			System.out.println((char) a);
		}
	} catch (IOException ioe){
		ioe.printStackTrace();
	} catch (Exception e){
		e.printStackTrace();
	} finally {
		try {
			if (bufferedIS != null) bufferedIS.close();
			if (inputStream != null) inputStream.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}

 

 

 

출력 스트림 연결

출력 수행 능력향상을 위해 BufferedOutputStream을 사용할 수 있다. BufferedOutputStream을 사용하면 출력내용이 있더라도 실제 출력이 되지 않을 수 있다. 버퍼를 비워줘야 하기 때문이다. flush() 메서드를 사용해 강제로 버퍼를 비워야 내용이 출력된다.

 

참고로 버퍼의 크기를 지정하지 않는경우 크기는 8192byte(=8kb)로 자동 설정된다. 출력할 내용이 8192바이트가 되지 않으면 버퍼에 그대로 남아있어 출력되지 않는다.

 

 

아래 코드를 보자

OutputStream과 BufferedOutputStream을 연결했다

public static void main(String[] args) {
	OutputStream outputStream = null;
	BufferedOutputStream bufferedOS = null;
	try {
		String fileName = "D:/Programming/_temp/test11.txt";
		outputStream = new FileOutputStream(fileName);
		bufferedOS = new BufferedOutputStream(outputStream);
		String message = "hello world";
		bufferedOS.write(message.getBytes());
		bufferedOS.flush();
	} catch (IOException ioe){
		ioe.printStackTrace();
	} catch (Exception e){
		e.printStackTrace();
	} finally {
		try {
			if (bufferedOS != null) bufferedOS.close();
			if (outputStream != null) outputStream.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}