Chapter 9 |
Buffered streams
Sometimes, the data needs to be buffered in between I/O operations. For example, an I/O operation may trigger a slow operation like a disk access or some network activity. These expensive operations can bring down overall performance of the application. As a result, to reduce the quagmire, Java platform implements a buffered (buffer=memory area) I/O stream. On invocation of an input operation, the data first is read from the buffer. If no data is found, a native API is called to fetch the content from an I/O device. Calling a native API is expensive, but if the data is found in the buffer, it is quick and efficient. Buffered stream is particularly suitable for I/O access dealing with huge chunks of data.
Some useful classes for reading/writing data in large portions are BufferedInputStream
and BufferedOutputStream
:
InputStream sisse = new BufferedInputStream(new FileInputStream("myPicture.jpg")); OutputStream välja = new BufferedOutputStream(new FileOutputStream("mySecondPicture.jpg"));
The buffer of BufferedInputStream
has a 8KiB-byte array by default, which holds the data from a stream. This helps increase the speed of reading/writing and data processing.
Apart from the buffered byte input stream, Java has a class for reading characters using a buffer - BufferedReader
. This class also looks for the lines in some buffered text:
InputStream myBytes = new FileInputStream("myInput.txt"); InputStreamReader myText = new InputStreamReader(myBytes, "UTF-8"); BufferedReader myBuffer = new BufferedReader(myText); String myLine = myBuffer.readLine(); while (myLine != null) { System.out.println("Line: " + myLine); myLine = myBuffer.readLine(); // reads the next line; if there is no line, null is returned } myBuffer.close();
The first three lines can be shortened as follows:
BufferedReader myBufferbr = new BufferedReader(new InputStreamReader(new FileInputStream("myInput.txt"), "UTF-8"));
Chapter 9 |