How to write file using BufferedOutputStream class in java?

Below code shows how to write file using BufferedOutputStream class in java –

/****************************************************************************************
 * Created on 08-2011 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javaio;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by http://kodehelp.com
 * Date: 8/30/11
 */
public class FileWriteExample {
    public static void main(String args[]){
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream("/tmp/testfile.txt"));
            //Start writing to the output stream
            bos.write("Here you go with Line one".getBytes());
            bos.write("\n".getBytes()); //new line, you might want to use \r\n if you're on

            bos.write("Here you go with Line two".getBytes());
            bos.write("\n".getBytes());

            //prints the character that has the decimal value of 65
            bos.write(65);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.flush();
                    bos.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Please Post Your Comments & Reviews

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.