JAVA 读取文件出现乱码的解决方案

今天在解析一个文本文件的时候出现了乱码,以前从未遇到,花了点时间上网解决了,在此总结一下:
首先,先看一下解析的代码:

public List<String> readLog(String logName){
List<String> picName = new ArrayList<String>();
String fileName = "D:\\"+logName;
BufferedReader br = null;
File file = new File(fileName);
try {
br = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = br.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
String[] arr = tempString.split("\t");
for(int i=0;i<arr.length;i++){
if(arr[i].contains(".jpg")){
picName.add(arr[i]);
break;
}
}
}
br.close();
return picName;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e1) {
}
}
}

}


这个方法很简单,就是获取文件中的一行数据,然后转换为数组,然后收集图片名,文本中包含中文。就这种情况下获取到的str是乱码,我想出现乱码肯定是字符集编码的问题,查看文件发现是Unicode编码(如何查看文件的编码呢,教你一个笨笨的办法:打开文件——另存为,然后看到最下面的编码,默认选择的就是当前文档的编码格式),问题就出现在这里。问题找到了就好解决了,修改代码为:
public List<String> readLog(String logName){
List<String> picName = new ArrayList<String>();
String fileName = "D:\\"+logName;
BufferedReader br = null;
File file = new File(fileName);
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = br.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
String[] arr = tempString.split("\t");
for(int i=0;i<arr.length;i++){
if(arr[i].contains(".jpg")){
picName.add(arr[i]);
break;
}
}
}
br.close();
return picName;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e1) {
}
}
}

}

使用文件流读取,转换编码为“UTF-8”,这样乱码问题就解决了。 归纳一下:文本文档有四种编码选项:ANSI、Unicode、Unicode big endian、UTF-8;默认应该是ANSI选项,就是系统的默认编码,一般是GBK,这种情况下用第一段代码解析是没有问题的,也不需要转码;其他格式就需要用第二段代码对应转码了,Unicode对应UTF-16,UTF-8就不用说了。 关于获取txt文件编码,我们可能有时候需要用程序获取,动态判断,这里给一点资料,参考参考:
ANSI: 无格式定义
Unicode: 前两个字节为FFFE Unicode文档以0xFFFE开头
Unicode big endian: 前两字节为FEFF
UTF-8: 前两字节为EFBB UTF-8以0xEFBBBF开头
用程序取出前几个字节并进行判断即可,具体参考链接:[url]http://wenku.baidu.com/view/95f2165577232f60ddcca1a5.html[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值