Filewriter and Fileoutputstream: when should I work with each of them?

Asked

Viewed 763 times

1

Often we find codes that could be solved with the use of objects of the type FileWriter or FileOutputStream. For example, a simple code that writes "Teste" in the archive /tmp/arquivo:

With FileWriter:

BufferedWriter output = new BufferedWriter(new FileWriter("/tmp/arquivo"););
output.write("Teste");

With FileOutputStream:

FileOutputStream file = new FileOutputStream(new File("/tmp/arquivo"));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(file));
output.write("Teste");

This happens when we are dealing with characters (another example would be a program that copies content from one file to another). When we are dealing with different files such as images, the FileWriter is no longer appropriate. But what are the implications of using FileOutputStream and FileWriter with character streams? Is one considered better than the other in this case? Is there a difference?

1 answer

4


Introducing

As we know, the classes Writer have an extra functionality around the classes OutputStream which is character conversion. When you use a Writer, you work with String and char[], while with OutputStream you can only use byte[].

Conversion of streams to Writers

But if you have one OutputStream any (such as a FileOutputStream) it is possible to convert it to a Writer if you use a OutputStreamWriter, as you did in the question example. The result will be the same.

Which to choose?

new Filewriter(...) or new Outputstreamwriter(new Fileoutputstream(...))?

First, what the official documentation says:

http://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.html http://docs.oracle.com/javase/8/docs/api/java/io/OutputStreamWriter.html

So, Filewriter uses the default encoding and Outputstreamwriter lets you choose the encoding of the generated file.

And, according to the code of JDK 8, in a very recent version (October 7, 2016),

http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/141beb4d854d/src/share/classes/java/io/FileWriter.java

the implementation of Filewriter simply inherits the entire implementation of Outputstreamwriter and only implements builders of convenience for the most common cases.

So, it is concluded that there is no difference between them when the standard JVM encoding is sufficient. You can then use the shortest form, with Filewriter.

Outputstreamwriter can be used to choose character encoding manually and also has another use: when you receive an Outputstream that you didn’t build and you need to convert it into a Writer to write Strings to it more conveniently.

For non-text files, of course, use a Fileoutputstream without converting it to Outputstreamwriter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.