Share on Google+Share on Google+

Java BufferedInputStream

Advertisement
This section demonstrates you the use of BufferedInputStream class.

Java BufferedInputStream

This section demonstrates you the use of BufferedInputStream class.

Java has provide a wrapper input stream called BufferedInputStream.  It has the ability to buffer the input. You can read bytes from this stream without necessarily causing a call to the underlying system for each byte read. Here we are going to read the file using this class.

In the given example, we have created an instance of BufferedInputStream class and wrapped the FileInputStream class. Then we have called read() method through the object of BufferedInputStream using while loop to read the file till the end of the file and stored the data in the form of bytes. The read() method read multiple bytes from the file into a buffer and then serve us bytes from the buffer. The bytes is then converted into string in order to display it on the console in a readable form.

Here is the code:

import java.io.*;

public class BufferedInputStreamExample {
	public static void main(String[] args) throws Exception {
		byte[] by = new byte[1024];
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				"C:/file.txt"));

		int i = 0;
		while ((i = bis.read(by)) != -1) {
			String st = new String(by, 0, i);
			System.out.print(st);
		}
		bis.close();
	}
}

Output:

Hello World

All glitters are not gold.
Truth is better than facts.
A man is not old until regrets take the place of dreams.

Advertisements

Posted on: July 3, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.