Java Buffered Input and Output Streams

If a large amount of data is being read from a source or written to a destination, buffering will make the processing more efficient. Instead of accessing the destination for every write,by using a buffered output stream, data is written to a buffer; when the buffer is full, it is sent to the destination with one write. Similarly, with a buffered read operation, the buffer
is filled with a single read. If the stream is a file stream, then both the source and destination will typically be a disk file. Buffered streams are used in conjunction with character or byte streams. BufferedReader and BufferedWriter are buffered streams used to wrap any character Reader or Writer stream; for file streams, these are FileReader and FileWriter, respectively. BufferedInputStream and BufferedOutputStream are buffered streams used to wrap any byte InputStream or OutputStream; for file streams, these are FileInputStream and FileOutputStream, respectively.

When creating a buffered stream using the buffered stream constructor, you can specify a buffer size or use the default size.

The following sections illustrate the BufferedReader and BufferedWriter streams. BufferedInputStream and BufferedOutputStream are handled in a similar manner, so we have not shown any examples of these.

So the statement in line 12 of ReadFile,

FileReader in = new FileReader(inputFile);

is equivalent to

FileInputStream fin = new FileInputStream(inputFile);
InputStreamReader in = new InputStreamReader(fin);


Like OutputStreamWriter, InputStreamReader also has a constructor for specifying non-default character-encoding schemes.

No comments:

Post a Comment