Java BufferedOutputStream Example

If you are writing the very much IO intensive application which needs to write huge amount of data to the files, then you have to do some kind of buffering to improve the performance. Here BufferedOutputStream will be helpful for writing the stream of characters into a file which internally manages a buffer for improving the performance. This class has to be wrapped with the FileOutputStream for opening the file. BufferedOutputStream has the following two constructors.

  • BufferedOutputStream(OutputStream out) – Creates a new buffered output stream to write data to the specified underlying output stream.
  • BufferedOutputStream(OutputStream out, int size) – Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.

It inherits all the methods from the FileOutputStream and defines the few new methods.

  • flush() – Flushes this buffered output stream.
  • write(byte[] b, int off, int len) -Writes len bytes from the specified byte array starting at offset off to this buffered output stream.
  • write(int b) – Writes the specified byte to this buffered output stream.

Lets look at the example to understand how to use BufferedOutputStream.



 * Java BufferedOutputStream Example
 * @author Krishna
public class BufferedOutputStreamExample {
	public static void main (String args[]) throws IOException{
		//Creating file output stream instance
		OutputStream file = new FileOutputStream("TextFile.txt");

		//Creating buffered output stream instance
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(file);
		String str = "This is example for BufferedOutputStream";

		//Gets byte array
		byte b[] = str.getBytes();

		//Writing byte array to a file

		//Writing a single byte

		//Writing a sequence of byte
		bufferedOutputStream.write(b, 5, 10);

		//Closing the stream

When you run the above program, file names “TextFile.txt” will be created with the given string values.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!