开发者

Java 7: What charset shall I use when calling Files.newBufferedReader?

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开发者_如何学C 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.


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.


PrintWriter/PrintStream in Java has by default Charset.defaultCharset()

java.nio.charset.Charset.defaultCharset()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜