感谢您的时间,当我的应用程序在 line 运行mycode = "UTF-8"
并直接跳转到 catch 时。这很奇怪,因为我只将值设置为字符串 mycode。此外,当我读取由 ANSI 编码的 txt 文件时,值为head[0]
,head[1]
而head[2]
不是-17``-69
并且-65
,所以条件应该是不满意的。但事实是应用程序仍然执行句子mycode = "UTF-8"
。我不知道原因,任何帮助将不胜感激。
我的代码如下:
package com.example.tyghgy;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import android.util.Log;
public class MyTxt {
private BufferedReader br = null;
InputStream in = null;
public MyTxt(){
File f=null;
f= new File("/sdcard/s.txt");
String sssss;
try {
in = new BufferedInputStream(new FileInputStream(f));
sssss = get_code();
} catch (FileNotFoundException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
try {
br = new BufferedReader(new InputStreamReader(in, "utf-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private String get_code(){
String mycode = "";
byte[] head = new byte[3];
try{
in.read(head);
if (head[0] == -1 && head[1] == -2 )
mycode = "UTF-16";
if (head[0] == -2 && head[1] == -1 )
mycode = "Unicode";
if(head[0]==-17 && head[1]==-69 && head[2] ==-65)
mycode = "UTF-8";
return mycode;
}catch (Exception e) {
// TODO: handle exception
Log.v("sssssssssss", e.getMessage());
mycode = e.getMessage();
return mycode;
}
}
}