본문 바로가기

Java Programming

Stream - Line-Oriented I/O, BufferedStream ②

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
Most of the examples we've seen so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

원문을 읽어보면 앞에서 다루었던 예제들은 unbuffered I/O 라는 것을 알 수 있습니다. unbuffered I/O 라는 것은 입출력을 요청하는 과정이 OS 하에서 직접적으로 조종이 된다는 것을 의미합니다. 다시 말하면 프로그램을 비 효율적으로 만든다는 것을 의미 한답니다. 쉽게 이야기 하자면, 한개의 input이 발생하면 또 바로 한개의 output을 생성하여 넘겨주는 방식이고 그러므로 입력할 것이 발생할때마다 발생한 숫자만큼 출력물(객체)을 생성해야하기 때문에 퍼포먼스가 떨어진다는 것을 의미하는 것 같습니다.

이런 오버헤드(지나치게 많이 프레임을나누어서 헤더의 양이 많아지면서 실제 전송할 전송량만큼이나 헤더의 용량이 커지는 현상)를 방지하기 위해서 자바에서는 buffered I/O stream 이라는 것을 구현 했다고 합니다. Buffer라고 불리우는 메모리로부터 데이터를 읽고 쓰는 방식이라고 합니다.

inputStream =
new BufferedReader(new FileReader("xanadu.txt"));
outputStream =
new BufferedWriter(new FileWriter("characteroutput.txt"));
위는 unbuffered stream을 buffered stream으로 변환시키는 과정이며, FileReader와 FileWriter의 객체가 BufferedReader와 BufferedWriter 클래스의 생성자를 거치면서 buffered stream으로 변환이 된다.


Flushing Buffered Streams

It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer.

Some buffered output classes support autoflush, specified by an optional constructor argument. When autoflush is enabled, certain key events cause the buffer to be flushed. For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format. See Formatting for more on these methods.

To flush a stream manually, invoke its flush method. The flush method is valid on any output stream, but has no effect unless the stream is buffered.

Flushing Buffered Stream 이라는것이 나오는데 flush는 쏟다, 분출하다, 넘치다 라는 의미를 가지고 있습니다. Stream에는 flush() 라는 메소드가 존재하는데 보통 buffer는 메모리가 가득 찼을 경우에 write out 하는데 강제적으로 buffer에 있는 stream을 내어 놓게 하는 메소드 입니다. 보통은 autoflush를 생성자의 인수를 통해서 설정할 수 있다고 합니다. flush() 메소드 같은 경우에는 ouput Stream의 경우에만 유효하며 buffered stream의 경우에는 영향을 주지 않는다고 합니다.