FileWrite BufferedWriter and PrintWriter combined

Ahoura Ghotbi picture Ahoura Ghotbi · Apr 4, 2013 · Viewed 21k times · Source

Ok so I am learning about I/O, and I found the following code in one of the slides. can someone please explain why there is a need to have a FileWrite, BufferedWriter and PrintWriter? I know BufferedWriter is to buffer the output and put it all at once but why would they use FileWriter and PrintWriter ? dont they pretty much do the same with a bit of difference in error handling etc?

And also why do they pass bw to PrintWriter?

      FileWriter fw = new FileWriter (file);
      BufferedWriter bw = new BufferedWriter (fw);
      PrintWriter outFile = new PrintWriter (bw);

Answer

Jon Skeet picture Jon Skeet · Apr 4, 2013

Presumably they're using a FileWriter because they want to write to a file. Both BufferedWriter and PrintWriter have to be given another writer to write to - you need some eventual destination.

(Personally I don't like FileWriter as it doesn't let you specify the encoding. I prefer to use FileOutputStream wrapped in an OutputStreamWriter, but that's a different matter.)

BufferedWriter is used for buffering, as you say - although it doesn't buffer all the output, just a fixed amount of it (the size of the buffer). It creates "chunkier" writes to the underlying writer.

As for the use of PrintWriter - well, that exposes some extra methods such as println. Personally I dislike it as it swallows exceptions (you have to check explicitly with checkError, which still doesn't give the details and which I don't think I've ever seen used), but again it depends on what you're doing. The PrintWriter is passed the BufferedWriter as its destination.

So the code below the section you've shown will presumably write to the PrintWriter, which will write to the BufferedWriter, which will (when its buffer is full, or it's flushed or closed) write to the FileWriter, which will in turn convert the character data into bytes on disk.