FileOutputStream vs. FileWriter

When we use Java to write something to a file, we can do it in the following two ways. One uses FileOutputStream, the other uses FileWriter.

Using FileOutputStream:

File fout = new File(file_location_string);
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
out.write("something");

Using FileWriter:

FileWriter fstream = new FileWriter(file_location_string);
BufferedWriter out = new BufferedWriter(fstream);
out.write("something");

Both will work, but what is the difference between FileOutputStream and FileWriter?

There are a lot of discussion on each of those classes, they both are good implements of file i/o concept that can be found in a general operating systems. However, we don’t care how it is designed, but only how to pick one of them and why pick it that way.

From Java API Specification:

FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

If you are familiar with design patterns, FileWriter is a typical usage of Decorator pattern actually. I have use a simple tutorial to demonstrate the Decorator pattern, since it is very important and very useful for many designs.

One application of FileOutputStream is converting a file to a byte array.

3 thoughts on “FileOutputStream vs. FileWriter”

  1. FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

    Если следовать “красоте кода”, для string – FileWriter, для byte – FileOutputStream

  2. эх.. Так и не понял, в чем конкретно разница 🙁

Leave a Comment