FileReader读取中文txt文件编码丢失问题
来源:互联网 发布:数据库设计经典案例 编辑:程序博客网 时间:2024/05/01 02:43
有一个UTF-8编码的文本文件,用FileReader读取到一个字符串,然后转换字符集:str=new String(str.getBytes(),"UTF-8");结果大部分中文显示正常,但最后仍有部分汉字显示为问号!
Java代码
public static List<String> getLines(String fileName){
List<String> lines=new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
lines.add(new String(line.getBytes("GBK"),"UTF-8"));
}
br.close();
} catch (FileNotFoundException e) {
}catch (IOException e) {}
return lines;
}
public static List<String> getLines(String fileName){
List<String> lines=new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
lines.add(new String(line.getBytes("GBK"),"UTF-8"));
}
br.close();
} catch (FileNotFoundException e) {
}catch (IOException e) {}
return lines;
}
文件读入时是按OS的默认字符集即GBK解码的,我先用默认字符集GBK编码str.getBytes(“GBK”),此时应该还原为文件中的字节序列了,然后再按UTF-8解码,生成的字符串按理说应该就应该是正确的。
为什么结果中还是有部分乱码呢?
问题出在FileReader读取文件的过程中,FileReader继承了InputStreamReader,但并没有实现父类中带字符集参数的构造函数,所以FileReader只能按系统默认的字符集来解码,然后在UTF-8 -> GBK -> UTF-8的过程中编码出现损失,造成结果不能还原最初的字符。
原因明确了,这个问题解决起来并不困难,用InputStreamReader代替FileReader,InputStreamReader isr=new InputStreamReader(new FileInputStream(fileName),"UTF-8");这样读取文件就会直接用UTF-8解码,不用再做编码转换。
Java代码
public static List<String> getLines(String fileName){
List<String> lines=new ArrayList<String>();
try {
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
lines.add(line);
}
br.close();
} catch (FileNotFoundException e) {
}catch (IOException e) {}
return lines;
}
- FileReader读取中文txt文件编码丢失问题
- FileReader读取中文txt文件编码丢失问题(乱码)
- FileReader读取文件中文乱码问题
- HTML5 FileReader 读取txt文件
- BufferedReader和FileReader读取txt文件乱码问题
- BufferedReader和FileReader读取txt文件乱码
- python2 读取文件TXT编码问题
- 从ANSI编码格式txt文件中读取中文
- java读取、写入(读写)txt文件中文乱码问题(相对应编码)及修改eclipse默认编码
- FileReader读取中文字符乱码问题
- Qt读取文件中文编码问题
- <转>BufferedReader和FileReader读取txt文件乱码
- 【string编码格式】Android读取txt文件乱码问题
- 【Android】读取txt文件的内容以及其编码问题
- qt读取中文txt文件
- Andoird - 解决读取txt文件中文乱码问题
- android读取txt文件中文乱码的问题
- python读取txt文件时的中文乱码问题
- (HTML学习)常用标签 超链接颜色控制
- HDUJ 1013 Digital Roots
- JavaFX文档(2)什么是JavaFX
- EBS R12多组织访问控制
- C++ map的基本操作和使用
- FileReader读取中文txt文件编码丢失问题
- 走好下一步为要
- HDU1285 确定比赛名次 【拓扑排序】
- 程序员的自我修养——操作系统篇
- C/C++ sort函数的用法
- iOS 面试题总结 (二)
- c语言除号,计算结果是小数要写成 4.0/3.0
- POJ-2010-优先队列(解题报告)
- UITableView:下拉刷新和上拉加载