Java读取文本文件中文乱码问题

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

List<String> lines=new ArrayList<String>();  
BufferedReader&nbsp;br&nbsp;=&nbsp;new&nbsp;BufferedReader(new&nbsp;FileReader(fileName));
String&nbsp;line&nbsp;=&nbsp;null;
while&nbsp;((line&nbsp;=&nbsp;br.readLine())&nbsp;!=&nbsp;null)&nbsp;{ 
      lines.add(line);
}
br.close();


后来百度和Google了以后,终于找到缘由,仍是从原理开始讲吧:ide


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


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


通过上述分析,修改以后的代码以下:it

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();
相关文章
相关标签/搜索