2

What encoding/character set does Java use per default when we create a new BufferedReader object without providing an encoding explicitly?

For example:

try (final BufferedReader reader = new BufferedReader(new FileReader("my_file.txt"))) {
  reader.readLine(); // What encoding is used to read the file?
}
1

2 Answers 2

5

BufferedReader doesn't do any decoding. It is a wrapper for another Reader ... which may or may not do decoding.

FileReader decodes using the JVM's default character encoding, as returned by Charset.defaultCharset()

The javadoc states:

Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

Sign up to request clarification or add additional context in comments.

Comments

4

FileReader is an InputStreamReader which uses FileInputStream as input, and an InputStreamReader uses the default charset when constructed without specified charset.

In the source code jdk10, it use Charset.defaultCharset():

public static StreamDecoder forInputStreamReader(InputStream in,
                                                 Object lock,
                                                 String charsetName)
    throws UnsupportedEncodingException
{
    String csn = charsetName;
    if (csn == null)
        csn = Charset.defaultCharset().name(); // get default charset
    try {
        if (Charset.isSupported(csn))
            return new StreamDecoder(in, lock, Charset.forName(csn));
    } catch (IllegalCharsetNameException x) { }
    throw new UnsupportedEncodingException (csn);
}

which

Returns the default charset of this Java virtual machine.

The default charset is determined during virtual-machine startup and typically depends upon the locale and charset of the underlying operating system.

You can print it:

public static void main(String[] args) {
    System.out.println(Charset.defaultCharset());
}

1 Comment

You should include an actual JavaDoc reference which connects this to FileReader; I could not find one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.