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.

Category >> Versus  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. maxslon on 2013-11-24

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

  2. Naveen on 2015-2-13

    🙂 Thanks 🙂

  3. Sergey on 2015-10-17

    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

Leave a comment

*