這幾天在研究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;
}
}