Java 7:调用Files.newBufferedReader时应使用什么字符集? [英] Java 7: What charset shall I use when calling Files.newBufferedReader?

查看:311
本文介绍了Java 7:调用Files.newBufferedReader时应使用什么字符集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以前的Java版本中,我会通过创建一个像这样的缓冲读取器来读取文件:

  BufferedReader in = new BufferedReader(new FileReader(file.txt)); 

在Java 7中,我想使用 Files.newBufferedReader ,但是我还需要传入一个字符集。例如:

  BufferedReader in = Files.newBufferedReader(Paths.get(file.txt),
Charset .forName( US-ASCII));

以前,在阅读纯文本文件时,我不必担心字符集。我应该使用什么字符集?你知道在以前的Java版本默认使用什么字符集吗?我只是希望能够找到并替换旧的声明。

解决方案


以前,在阅读纯文本文件时,我不必担心字符集。

好的,你应该完成了。如果您只是使用 FileReader ,它使用系统的默认字符编码。这是一个坏主意,这就是为什么我总是使用 FileInputStream InputStreamReader 的原因。你应该永远明确它。如果您真的想为系统默认字符编码,您应该使用 Charset.defaultCharset() - 但我强烈建议您不要。

如果您要读取文件,您应该知道字符编码,并指定。如果你决定在文件中使用什么字符编码,UTF-8是一个很好的默认选择。

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.

解决方案

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.

这篇关于Java 7:调用Files.newBufferedReader时应使用什么字符集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆