Session 10 |
Stream buffering
Reading and writing the data is a relatively slow process. Sometimes it is not efficient to read data in small portions. Java has some more classes for reading/writing the data in large portions - 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 the 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 the 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 shorted as follows:
BufferedReader myBufferbr = new BufferedReader(new InputStreamReader(new FileInputStream("myInput.txt"), "UTF-8"));
Session 10 |