javafilestreamfilereaderbufferedreader

Difference between java.io.PrintWriter and java.io.BufferedWriter?


Please look through code below:

// A.class
File file = new File("blah.txt");
FileWriter fileWriter = new FileWriter(file);
PrintWriter printWriter = new PrintWriter(fileWriter);

// B.class
File file = new File("blah.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bWriter = new BufferedWriter(fileWriter);

What is the difference between these two methods?

When should we use PrintWriter over BufferedWriter?


Solution

  • The API reference for BufferedWriter and PrintWriter detail the differences.

    The main reason to use the PrintWriter is to get access to the printXXX methods like println(). You can essentially use a PrintWriter to write to a file just like you would use System.out to write to the console.

    A BufferedWriter is an efficient way to write to a file (or anything else), as it will buffer the characters in Java memory before (probably, depending on the implementation) dropping to C to do the writing to the file.

    There is no such concept as a "PrintReader"; the closest you will get is probably java.util.Scanner.