FileWriter vs FileOutputStream in Java
A FileOutputStream
writes bytes directly. A FileWriter
encapsulates a FileOutputStream
(by creating it in the FileWriter
constructor as in your question) and provides convenience methods to write characters and Strings.
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
.
FileOutputStream
is to write primitive types of data, like int
, while FileWriter
is to write character-oriented data.
FileOutputStream
does not come with methods to deal with strings. If you want to use FileOutputStream
to write a string to a file, you have to go like:
FileOutputStream fos=new FileOutputStream();
String str="Hello";
byte b[]=str.getBytes();
fos.write(b);
fos.close();
In Filewriter
there is no conversion between string and byte array. You could simply use:
FileWriter fr=new FileWriter("C:\\");
fr.write("Hello");
fr.close();
Do not forget to throw any exceptions if needed.