您的位置:首页 > 移动开发 > Android开发

彻底解决android读取中文txt,lrc的乱码(自动判断文档类型并转码)

2013-02-03 22:58 781 查看
这几天在研究android的播放器,在读取歌词的时候,老是乱码,使我很纠结:

今天在网上看到一个文件转码的文章,彻底解决了我的乱码问题,这样我就不用自己去手动的转码lrc歌词文件你的编码了,现在与大家分享一下这一文章(其中里面的几个if else里面的条件原理不是很懂,请高手帮忙解答):

package com.qgmobile.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* 转换文件的编码格式
* @author yangchuxi
*
*/
public class ConvertFileCode {
public String converfile(String filepath){
System.out.println("ConvertFileCode--------->"+filepath);
File file=new File(filepath);
FileInputStream fis=null;
BufferedInputStream bis=null;
BufferedReader reader=null;
String text="";
try {
fis=new FileInputStream(file);
bis=new BufferedInputStream(fis);
bis.mark(4);
byte[] first3bytes=new byte[3];
//   System.out.println("");
//找到文档的前三个字节并自动判断文档类型。
bis.read(first3bytes);
bis.reset();
if (first3bytes[0] == (byte) 0xEF && first3bytes[1] == (byte) 0xBB
&& first3bytes[2] == (byte) 0xBF) {// utf-8

reader = new BufferedReader(new InputStreamReader(bis, "utf-8"));

} else if (first3bytes[0] == (byte) 0xFF
&& first3bytes[1] == (byte) 0xFE) {

reader = new BufferedReader(
new InputStreamReader(bis, "unicode"));
} else if (first3bytes[0] == (byte) 0xFE
&& first3bytes[1] == (byte) 0xFF) {

reader = new BufferedReader(new InputStreamReader(bis,
"utf-16be"));
} else if (first3bytes[0] == (byte) 0xFF
&& first3bytes[1] == (byte) 0xFF) {

reader = new BufferedReader(new InputStreamReader(bis,
"utf-16le"));
} else {

reader = new BufferedReader(new InputStreamReader(bis, "GBK"));
}
String str = reader.readLine();

while (str != null) {
text = text + str + "/n";
str = reader.readLine();
}
System.out.println("text"+text);
} catch (Exception e) {
e.printStackTrace();
}finally{
if (fis!=null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return text;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: