The Buffered Streams BufferedOutputStream - RameshMF/java-io-guide GitHub Wiki

Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.

For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax for adding the buffer in an OutputStream:

OutputStream os= new BufferedOutputStream(new FileOutputStream("sample.txt"));  

BufferedOutputStream class 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.

BufferedOutputStream class Methods

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

BufferedOutputStream class Example

This program uses below text content as input and write to file named "sample.txt".

String content = "This is the text content";

Note : This program uses try-with-resources. It requires JDK 7 or later.


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * The class demonstrate the usage of BufferedOutputStream class methods.
 * @author javaguides.net
 *
 */

public class BufferedOutputStreamExample {
	public static void main(String[] args) {
		File file = new File("sample.txt");
		String content = "This is the text content";

		try (OutputStream out = new FileOutputStream(file);
				BufferedOutputStream bout = new BufferedOutputStream(out);) {

			// if file doesn't exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}
			// get the content in bytes
			bout.write(content.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Reference

BufferedOutputStream Javadoc 8