怎样获得txt文件的字符集?
我想实现这样的功能,通过socket接收下来一个stream,存成txt文本,
以上的过程是模拟手机接收文本信息的过程。由于手机只能阅读utf8字符集的文本,所以我想判断一下这个stream或者是已经储存的这个文本字符集是否是utf8的。如何实现?
我尝试了以下方法:
public static boolean isCharSet(File file)
{
//读取文件
int readLenght=100;
byte[] hb=new byte[readLenght];
FileInputStream fos;
ByteBuffer bytebuffer=ByteBuffer.allocate(readLenght);
try {
fos = new FileInputStream(file);
int readint;
do{
readint=fos.read(hb);
bytebuffer.put(hb);
if(readint==readLenght){
bytebuffer=ByteBuffer.allocate(bytebuffer.limit()+readLenght);
}
}while(readint==readLenght);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
//对字符集的判断,主要看这里
Charset decodeCharset = Charset.forName("UTF-8");
CharsetDecoder decoder = decodeCharset.newDecoder();
CharBuffer cb = null;
try
{
cb = decoder.decode(bytebuffer);
System.out.println("yes");
return true;
}
catch (CharacterCodingException ex)
{
System.out.println("no");
return false;
}
}
可是对任何的字符集的txt文件都返回yes,请高人指点。