I have always been slightly confused with the amount of different IO implementations in Java, and now that I am completely stuck in my project development, I was taking my time
FileWriter
is generally not an acceptable class to use. It does not allow you to specify the Charset
to use for writing, which means you are stuck with whatever the default charset of the platform you're running on happens to be. Needless to say, this makes it impossible to consistently use the same charset for reading and writing text files and can lead to corrupted data.
Rather than using FileWriter
, you should be wrapping a FileOutputStream
in an OutputStreamWriter
. OutputStreamWriter
does allow you to specify a charset:
File file = ...
OutputStream fileOut = new FileOutputStream(file);
Writer writer = new BufferedWriter(new OutputStreamWriter(fileOut, "UTF-8"));
To use PrintWriter
with the above, just wrap the BufferedWriter
in a PrintWriter
:
PrintWriter printWriter = new PrintWriter(writer);
You could also just use the PrintWriter
constructor that takes a File
and the name of a charset:
PrintWriter printWriter = new PrintWriter(file, "UTF-8");
This works just fine for your particular situation, and actually does the exact same thing as the code above, but it's good to know how to build it by wrapping the various parts.
The other Writer
types are mostly for specialized uses:
StringWriter
is just a Writer
that can be used to create a String
. CharArrayWriter
is the same for char[]
.PipedWriter
for piping to a PipedReader
.Edit:
I noticed that you commented on another answer about the verbosity of creating a writer this way. Note that there are libraries such as Guava that help reduce the verbosity of common operations. Take, for example, writing a String
to a file in a specific charset. With Guava you can just write:
Files.write(text, file, Charsets.UTF_8);
You can also create a BufferedWriter
like this:
BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8);