Monday, September 16, 2019

Buffered Streams in Java IO

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

  1. getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java
  2. How to Count Lines in a File in Java
  3. Creating Temporary File in Java
  4. Reading Delimited File in Java Using Scanner
  5. How to Create PDF in Java Using OpenPDF

You may also like-

  1. Converting String to int in Java
  2. continue Statement in Java With Examples
  3. ResultSet Interface in Java-JDBC
  4. Method Reference in Java
  5. AutoBoxing And UnBoxing in Java
  6. Java Stream API Interview Questions And Answers
  7. Configuring DataSource in Spring Framework
  8. registerShutdownHook() Method in Spring Framework

No comments:

Post a Comment