很多Android开发者在读取含有双字节字符的txt文件的时候,可能会中文乱码问题,解决办法如下:
private String getTextString(String pathandname) throws IOException{
String str = "";
FileInputStream fis = new FileInputStream(pathandname);
//InputStreamReader isr = new InputStreamReader(fis, "gbk");
//BufferedReader br = new BufferedReader(isr);
int size = fis.available();
byte[] buffer = new byte[size];
fis.read(buffer);
fis.close();
str = new String(buffer, "GBK");//支持双字节字符
myApp.setCharNumofString(str.length());//存储总字符数
return str;
}
下面附带一个检测txt文件中是否含有双字节字符的方法,主要功能:检测txt文件中是否含有双字节字符,若有返回假,否则返回真。
public
static
boolean
isRightfulTXT(File f) {
String regexp =
"[^\\x00-\\xff]"
;
//双字节字符
Pattern p = Pattern.compile(regexp);
try
{
FileInputStream fis =
new
FileInputStream(f);
//"GBK"编码方式支持双字节字符
InputStreamReader isr =
new
InputStreamReader(fis,
"GBK"
);
BufferedReader br =
new
BufferedReader(isr);
String line =
""
;
while
((line = br.readLine()) !=
null
){
//循环读取文件每一行,检测是否含有双字节字符
Matcher m = p.matcher(line);
if
(m.find()) {
fis.close();
isr.close();
br.close();
return
false
;
}
}
fis.close();
isr.close();
br.close();
}
catch
(FileNotFoundException e) {
e.printStackTrace();
}
catch
(UnsupportedEncodingException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
return
true
;
}