In our Java IO Stream classes tutorial we have already seen the Byte stream classes in Java and character stream classes in Java. But using these classes directly, without any buffering, results in very inefficient reading or writing of streams in turn making you program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. To make IO operations more efficient the Java platform implements buffered I/O streams.
Buffered streams in Java
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.
Buffered stream wraps the unbuffered stream to convert it into a buffered stream. For that unbuffered stream object is passed to the constructor for a buffered stream class. For example wrapping FileReader and FileWriter to get BufferedReader and BufferedWriter.
BufferedReader br = new BufferedReader(new FileReader("abc.txt")); BufferedWriter bw = new BufferedWriter(new FileWriter("write.txt"));
Buffered streams classes in Java
There are four buffered stream classes-
BufferedInputStream and BufferedOutputStream are used to wrap unbuffered byte streams to create buffered byte streams.
BufferedReader and BufferedWriter are used to wrap unbuffered character streams to create buffered character streams.
Flushing buffered streams
Since the characters or bytes are stored in a buffer before writing to the file so flushing the buffer is required sometimes without waiting for it to fill. There is an explicit flush() method for doing that. In most buffered stream implementations even close() method internally calls flush() method before closing the stream. Note that the flush method is valid on any output stream, but has no effect unless the stream is buffered.
That's all for this topic Buffered Streams in Java IO. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Advanced Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment