Write to file using a BufferedWriter



When you want to output text to a file it’s better to use a Writer class instead of an OutputStream such as the BufferedOutputStream since the purpose of Writer classes are to handle textual content.
With the BufferedWriter (as opposed to the BufferedOutputStream) you don’t have to translate your String parameter to a byte array, and there is also a handy method for writing a new line character.
In this example we simply write two lines of text, and finally we call flush on the BufferedWriter object before closing it.

The output to the file will look like this when you run the code:







Search for more Java info on this site here:
Custom Search


3 thoughts on “Write to file using a BufferedWriter

    • Hi Daniel,

      A PrintWriter could be used. But the main advantages with a BufferedWriter is that it (like the name implies) buffers data before it actually writes it to the physical file. That makes it more efficient. In this little example it might not matter, but if large amounts of data will be written it does matter.

      Another advantage with the BufferedWriter is that it actually throws exceptions if something goes wrong. The PrintWriter’s methods however don’t throw any exceptions, so we can’t know if anything has gone wrong (some of the constructors do, but that’s all).

Any thoughts or questions?