본문 바로가기
Development/Java

FileOutputStream vs. FileWriter

by 신군. 2018. 9. 30.
반응형

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.


반응형

'Development > Java' 카테고리의 다른 글

Java Date 비교  (0) 2017.02.08