The stream hierarchy of classes help in writing binary data to the files as compared to reader/writer classes which deal with character data. Both the hierarchy of classes have buffered decorators for performing the read and write operations which improve the performance of the application.

The following program shows how to use the BufferedOutputStream object to write to a file:

package com.example;

 

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

 

/** This class is a Java tutorial for using BufferedOutputStream in Java

 *

 * @author Extreme Java

 */

public class Test{

 

    /** This method shows how to write to file using BufferedOutputStream in Java

     *

     * @param args

     * @throws IOException

     */

    public static void main(String[] args) throws IOException {

        String str = "Hi! This is a test string";

 

        byte[] b = str.getBytes();

 

        FileOutputStream fos =  new FileOutputStream(new File("c://test.txt"));

 

        BufferedOutputStream bos = new BufferedOutputStream(fos);

 

        bos.write(b);

 

        bos.flush();

    }

}

As one can see in the above program that we are getting the byte array for the string and then writing it to the file. Also the FileOutputStream class is being decorated by BufferedOutputStream.

Related Pages