FileReader读取文件中文乱码问题
来源:互联网 发布:unity3d 2d碰撞检测 编辑:程序博客网 时间:2024/05/22 08:10
有一个UTF-8编码的文本文件,用FileReader读取到一个字符串,然后转换字符集:str=newString(str.getBytes(),"UTF-8");结果大部分中文显示正常,但最后仍有部分汉字显示为问号!
Java代码
public static List<String> getLines(String fileName){
List<String> lines=newArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line= null;
while ((line= br.readLine()) != null) {
lines.add(newString(line.getBytes("GBK"),"UTF-8"));
}
br.close();
} catch (FileNotFoundException e){
}catch (IOException e){}
return lines;
}
public staticList<String> getLines(String fileName){
List<String> lines=new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(newFileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
lines.add(newString(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,InputStreamReaderisr=new
InputStreamReader(new FileInputStream(fileName),"UTF-8");这样读取文件就会直接用UTF-8解码,不用再做编码转换。
Java代码
public static List<String> getLines(String fileName){
List<String> lines=newArrayList<String>();
try {
BufferedReader br=new BufferedReader(new InputStreamReader(newFileInputStream(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读取文件中文乱码问题
- FileReader读取中文txt文件编码丢失问题(乱码)
- FileReader读取中文字符乱码问题
- BufferedReader和FileReader读取txt文件乱码问题
- FileReader读取中文txt文件编码丢失问题
- BufferedReader和FileReader读取txt文件乱码
- FileReader和BufferReader读取中文乱码问题,主要由源文件格式问题
- Java中 FileReader的中文乱码问题
- Java读取文件 解决中文乱码问题
- 文件读取之中文乱码问题
- Java IO读取文件中文乱码问题
- java读取文件中文乱码问题
- Java 读取xml文件中文乱码问题
- java 读取中文文件乱码问题
- Java读取properties文件 中文乱码问题
- Java IO读取文件中文乱码问题
- 解决FileInputStream 读取文件中文乱码问题
- nodejs文件读取中文乱码问题
- 如何成为一个牛逼的C/C++程序员?
- JsTree3.3搭建开发环境
- 一些Android题
- mysql 优化学习
- 第一章 对象导论
- FileReader读取文件中文乱码问题
- LVS+keepalived+mycat负载均衡及自动转发
- OpenGL学习笔记4_0(基本词汇和转换定义)
- 编写函数int stat(int a[],int n,int c[][2])
- ES6学习笔记
- 如何对栈进行简单的初级操作
- [SinGuLaRiTy-1002] Miller Rabin Prime Judge 米勒·罗宾素数判定法
- stable_sort()与sort()的用法区别
- iOS APP 上架证书打包