问题
In previous versions of Java, I would read a file by creating a buffered reader like this:
BufferedReader in = new BufferedReader(new FileReader("file.txt"));
In Java 7, I would like to use Files.newBufferedReader, but I need to pass in a charset as well. For example:
BufferedReader in = Files.newBufferedReader(Paths.get("file.txt"),
Charset.forName("US-ASCII"));
Previously, I did not have to worry about charsets when reading plain text files. What charset shall I use? Do you know what charset was used by default in previous versions of Java? I simply want to be able to find and replace the old statement with the new one.
回答1:
Previously, I did not have to worry about charsets when reading plain text files.
Well, you should have done. If you were just using FileReader
, it was using the default character encoding for the system. That was a bad idea, which is why I always used FileInputStream
and an InputStreamReader
. You should always be explicit about it. If you really want the default character encoding for the system, you should use Charset.defaultCharset() - but I strongly suggest that you don't.
If you're going to read a file, you should know the character encoding, and specify that. If you get to decide what character encoding to use when writing a file, UTF-8 is a good default choice.
回答2:
PrintWriter
/PrintStream
in Java has by default Charset.defaultCharset()
java.nio.charset.Charset.defaultCharset()
来源:https://stackoverflow.com/questions/6993218/java-7-what-charset-shall-i-use-when-calling-files-newbufferedreader