I'm little confused about FileWriter
and FileOutputStream
. As I see source code of FileWriter there are just 4 constructors and each constructor is calling FileOutputStream
's constructor.
public FileWriter(String fileName) throws IOException {
super(new FileOutputStream(fileName));
}
public FileWriter(String fileName, boolean append) throws IOException {
super(new FileOutputStream(fileName, append));
}
public FileWriter(File file) throws IOException {
super(new FileOutputStream(file));
}
public FileWriter(File file, boolean append) throws IOException {
super(new FileOutputStream(file, append));
}
public FileWriter(FileDescriptor fd) {
super(new FileOutputStream(fd));
}
After searching difference between them I found mentioned here.
FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.
How FileWriter
can make difference? Even it still calling FileOutputStream
's constructor without any changing.
FileWriter
is a Writer
. It's about writing text - and it happens to be writing it to a file. It does that by holding a reference to a FileOutputStream
, which is created in the FileWriter
constructor and passed to the superclass constructor.
FileOutputStream
is an OutputStream
. It's about writing binary data. If you want to write text to it, you need something to convert that text to binary data - and that's exactly what FileWriter
does. Personally I prefer to use FileOutputStream
wrapped in an OutputStreamWriter
by me to allow me to specify the character encoding (as FileWriter
always uses the platform default encoding, annoyingly).
Basically, think of FileWriter
is a simple way of letting you write:
Writer writer = new FileWriter("test.txt");
instead of
Writer writer = new OutputStreamWriter(new FileOutputStream("test.txt"));
Except I'd normally recommend using the overload of the OutputStreamWriter
constructor that accepts a Charset
.
See more on this question at Stackoverflow