BufferedWriter Tutorial

The BufferedWriter class is used to write text to a character stream. This tutorial builds on concepts from my BufferedReader Tutorial, OutputStreamWriter Tutorial, and my FileWriter Tutorial, I highly recommend watching them first. This tutorial will demonstrate writing to an output stream first to the console and then to a text file. The BufferedWriter class has three overloaded versions of the write() method, I will demonstrating the one that takes a String parameter. The BufferedWriter class introduces a method named newLine() which means that you will not have to hardcode in the "\r\n" into your output stream anymore. The BufferedWriter class implements AutoClosable so we can use the try-with-resources type exception handling.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md BW
C:\Java>cd BW
C:\Java\BW>Notepad BW.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


import java.io.*;
class BW {
    public static void main(String args[]) {
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out))) {
            bw.write("Type whatever you want to go into a file called Sample.txt,");
            bw.newLine();
            bw.write("type EXIT on a new line and Enter to stop writing to the file: ");
            bw.newLine();
        } catch(IOException e) {
            System.out.println(e.getMessage());
        }

        try (BufferedWriter bw = new BufferedWriter(new FileWriter("Example.txt"))) {
            bw.write("Hello BufferedWriter");
            bw.newLine();
            bw.write("Love the newLine() method :)");
            bw.newLine();
        } catch(IOException e) {
            System.out.println(e.getMessage());
        }

        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            String inputString = br.readLine();
            while(!inputString.equals("EXIT")){
                try (BufferedWriter bw = new BufferedWriter(new FileWriter("Sample.txt", true))) {
                    bw.write(inputString);
                    bw.newLine();
                } catch(IOException e) {
                    System.out.println(e.getMessage());
                }
                inputString = br.readLine();
            } 
        } catch(IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

Now switch back to the command prompt (CMD) and type in javac BR.java and press Enter.
Now type in java BR and press Enter.


C:\Java\BR>javac BR.java
C:\Java\BR>java BR
Type whatever you want to go into a file called Sample.txt,
type EXIT on a new line and Enter to stop writing to the file: 
results vary

Final thoughts

The BufferedWriter class comes in very handy for writing lines of text to a file.


Tutorials