Buffered Output Stream

Buffered Output Stream

It is used for buffering an output stream. To store the data, it uses an internal buffer. It helps in adding more efficiency than writing data directly into a stream. It is used to make the performance faster. To add the buffer in an OutputStream, we use the BufferedOutputStream class.

Syntax for declaring java.io.BufferedOutputStream class:

public class BufferedOutputStream extends FilterOutputStream

An application can write bytes to the underlying output stream without calling the underlying system for each byte written by setting up such an output stream.

Fields of Java Buffered Output stream:

  • protected byte[ ] buf: It is the internal buffer that stores the data.
  • protected int count:  It is the number of valid bytes available in the buffer.

Constructors of Java Buffered Output stream:

  • BufferedOutputStream(OutputStream out):  It creates the new buffered output stream for writing data to any specific underlying output stream.
  • BufferedOutputStream(OutputStream out, int size):  It creates a newer buffered output stream for writing data to any particular underlying output stream where the buffer size is specified.

Methods of Java Buffered Output stream:

  • void flush():  It helps to flush the buffered output stream.
  • void write(byte[] b, int off, int len):  It helps in writing len bytes from any specified byte array that starts at off offset to this buffered output stream class.
  • void write(int b):  It helps in writing a specific byte to this buffered output stream class.
  • Example :

    import java.io.*; class BufferedOutputStreamDemo { public static void main(String args[])throws Exception { FileOutputStream fout = new FileOutputStream("knowledge2life.txt"); BufferedOutputStream bout = new BufferedOutputStream(fout); for(int i = 65; i < 75; i++) { bout.write(i); } byte b[] = { 75, 76, 77, 78, 79, 80 }; bout.write(b); bout.flush(); bout.close(); fout.close(); } }