character encodings used by FileWriter, DataOutputStream, OutputStreamWriter and RandomAccessFile

196 Views Asked by At

FileWriter, DataOutputStream, OutputStreamWriter and RandomAccessFile can write character data to underlying streams or files, can anybody summarize what are the default character encodings they are using, can they be set to use other encodings than the default ones?

2

There are 2 best solutions below

1
On
  • FileWriter: uses the default encoding
  • DataOutputStream: doesn't write characters. Writes bytes. So encoding is irrelevant. Except for writeUTF(), which uses modified UTF8 encoding (read the documentation for more details)
  • OutputStreamWriter: uses the encoding passed as argument to the constructor
  • RandomAccessFile: doesn't write characters. Writes bytes. So encoding is irrelevant. Except for writeUTF(), which uses modified UTF8 encoding (read the documentation for more details)

All this is available by just reading the javadoc.

4
On

For OutputStreamWriter, if the charset is not specified, it will get the default charset from Charset.defaultCharset().name(); (which, if not identified will resort to using UTF-8). This is assuming that you are running an Oracle Java JDK where the class calls the StreamEncoder.forOutputStreamWriter which is a sun package.

DataOutputStream writes bytes so no encoding is needed.

RandomAccessFile reads and writes bytes so no encoding is needed.

FileWriter is a subclass of OutputStreamWriter so it'll use the default encoding used by OutputStreamWriter.

I hope this helps.