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

i2ijeya picture i2ijeya · Nov 17, 2009 · Viewed 81.2k times · Source

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?

Answer

Jon Skeet picture Jon Skeet · Nov 17, 2009

PrintWriter gives more methods (println), but the most important (and worrying) difference to be aware of is that it swallows exceptions.

You can call checkError later on to see whether any errors have occurred, but typically you'd use PrintWriter for things like writing to the console - or in "quick 'n dirty" apps where you don't want to be bothered by exceptions (and where long-term reliability isn't an issue).

I'm not sure why the "extra formatting abilities" and "don't swallow exceptions" aspects are bundled into the same class - formatting is obviously useful in many places where you don't want exceptions to be swallowed. It would be nice to see BufferedWriter get the same abilities at some point...