Write to file using a BufferedWriter


When you want to output text to a file it's better to use a Writer class instead of an OutputStream such as the BufferedOutputStream since the purpose of Writer classes are to handle textual content.
With the BufferedWriter (as opposed to the BufferedOutputStream) you don't have to translate your String parameter to a byte array, and there is also a handy method for writing a new line character.
In this example we simply write two lines of text, and finally we call flush on the BufferedWriter object before closing it.


import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

/**
 *
 * @author javadb.com
 */

public class Main {
    
    /**
     * Prints some data to a file using a BufferedWriter
     */

    public void writeToFile(String filename) {
        
        BufferedWriter bufferedWriter = null;
        
        try {
            
            //Construct the BufferedWriter object
            bufferedWriter = new BufferedWriter(new FileWriter(filename));
            
            //Start writing to the output stream
            bufferedWriter.write("Writing line one to file");
            bufferedWriter.newLine();
            bufferedWriter.write("Writing line two to file");
            
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the BufferedWriter
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().writeToFile("myFile.txt");
    }
}


The output to the file will look like this when you run the code:

Writing line one to file
Writing line two to file

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: