Thursday, February 21, 2008

Write to file using BufferedOutputStream

This code snippet shows how to write to a file using a BufferedOuputStream. Now it should be said that if you want to write text to a file you should probably find it easier to go with a Writer class like the BufferedWriter instead.
The write method of the BufferedOuputStream takes either a byte array or an int as argument so that is why we have to call getBytes() on any String that we provide to the write method. The getBytes method of the String class returns its content in the form of a byte array.
The other overloaded variant of the write method that takes an int as an argument prints the character that has the decimal value (or ascii value if you want) that matches the parameter. So in the example below we call write with 65 as the argument, which is the same as character 'A'.

Note that the construction of a BufferedOutputStream as below will overwrite any file with the same name that already exists.
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    
    /**
     * Prints some data to a file
     */
    public void writeToFile(String filename) {
        
        BufferedOutputStream bufferedOutput = null;
        
        try {
            
            //Construct the BufferedOutputStream object
            bufferedOutput = new BufferedOutputStream(new FileOutputStream(filename));
            
            //Start writing to the output stream
            bufferedOutput.write("Line one".getBytes());
            bufferedOutput.write("\n".getBytes()); //new line, you might want to use \r\n if you're on Windows
            bufferedOutput.write("Line two".getBytes());
            bufferedOutput.write("\n".getBytes());
            
            //prints the character that has the decimal value of 65
            bufferedOutput.write(65);
            
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the BufferedOutputStream
            try {
                if (bufferedOutput != null) {
                    bufferedOutput.flush();
                    bufferedOutput.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().writeToFile("myFile.txt");
    }
}

If you run the code the contents of the file should look like this:

Line one
Line two
A
 
Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By freecode-frecode.blogger.com & blogger.com Programming Blogs - BlogCatalog Blog Directory