FileWriter and FileOutputStream: When should I work with each of them?

1

Often we find codes that could be solved by using objects of type FileWriter or FileOutputStream . For example, a simple code that writes " Teste " in the file /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, 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?

    
asked by anonymous 11.10.2016 / 08:02

1 answer

4

Introduction

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

Conversion of streams to writers

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

Which one to choose?

new FileWriter (...) or new OutputStreamWriter (new FileOutputStream (...))

First, what the official documentation says:

link link

Then, FileWriter uses the default encoding and OutputStreamWriter allows you to choose the encoding of the generated file.

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

The implementation of FileWriter simply inherits the entire OutputStreamWriter implementation and only implements convenience constructors for the most common cases.

Then it turns out that there is no difference between them when the standard JVM encoding is sufficient. You can then use the shortest form, with FileWriter.

The OutputStreamWriter can be used to choose the character encoding manually and also has another use: when you receive an OutputStream that you did not build and need to convert it into a Writer to write Strings to it in a more convenient way. p>

Already for non-text files, obviously use a FileOutputStream without converting it to OutputStreamWriter.

    
13.10.2016 / 21:28