Java读取文本文件中文乱码问题(转)

xiaoxiao2021-02-28  89

最近遇到一个问题,Java读取文本文件(例如csv文件、txt文件等),遇到中文就变成乱码。读取代码如下:

[java]  view plain  copy List<String> lines=new ArrayList<String>();     BufferedReader br = new BufferedReader(new FileReader(fileName));   String line = null;   while ((line = br.readLine()) != null) {          lines.add(line);   }   br.close();  

后来百度和Google了之后,终于找到原因,还是从原理开始讲吧:

Java的I/O类处理如图:

Reader 类是 Java 的 I/O 中读字符的父类,而 InputStream 类是读字节的父类,InputStreamReader 类就是关联字节到字符的桥梁,它负责在 I/O 过程中处理读取字节到字符的转换,而具体字节到字符的解码实现它由 StreamDecoder 去实现,在 StreamDecoder 解码过程中必须由用户指定 Charset 编码格式。值得注意的是如果你没有指定 Charset,将使用本地环境中的默认字符集,例如在中文环境中将使用 GBK 编码。

                                    Java的I/O类处理图

总结:Java读取数据流的时候,一定要指定数据流的编码方式,否则将使用本地环境中的默认字符集。

经过上述分析,修改之后的代码如下:

[java]  view plain  copy List<String> lines=new ArrayList<String>();   BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"UTF-8"));   String line = null;   while ((line = br.readLine()) != null) {         lines.add(line);   }   br.close();  

参考资料:

http://www.ibm.com/developerworks/cn/java/j-lo-chinesecoding/

http://hi.baidu.com/annleecn/blog/item/154770ed900738db2e2e2151.html

http://sd8089730.iteye.com/blog/1290895

http://www.360doc.com/content/07/0403/09/16749_427888.shtml

转载请注明原文地址: https://www.6miu.com/read-40126.html

最新回复(0)