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.
package javabeat.net.io; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * 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 bufferedOutputStream.write(b); //Writing a single byte bufferedOutputStream.write(b[0]); //Writing a sequence of byte bufferedOutputStream.write(b, 5, 10); //Closing the stream bufferedOutputStream.close(); } }
When you run the above program, file names “TextFile.txt” will be created with the given string values.