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

Viewed 91114

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?

8 Answers

PrintWriter is the most enhanced Writer to write Character data to a file.

The main advantage of PrintWriter over FileWriter and BufferedWriter is:

  1. PrintWriter can communicate directly with the file, and can communicate via some Writer object also.

PrintWriter printwriter = new PrintWriter("blah.txt");

(or)

FileWriter filewriter = new FileWriter("blah.txt");
PrintWriter printwiter = new PrintWriter(filewriter);
  1. We can write any type of Primitive data directly to the file (because we have additional overloaded versions of PrintWriter methods i.e., print() and println()).

    printwriter.print(65); //65
    bufferedwriter.write(65); //A
    printwriter.println(true); //true

Related