我想实现这样的功能,通过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,请高人指点。
以上的过程是模拟手机接收文本信息的过程。由于手机只能阅读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,请高人指点。
读取前三个自己就是文本内容啊?那里能找到你说的0xEF 0xBB 0xBF??
InputStream is = new FileInputStream(FILENAME);
byte[] utf8head = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
byte[] b = new byte[3];
is.read(b);BufferedReader br = null;
if(Arrays.equals(utf8head, b)) {
br = new BufferedReader(new InputStreamReader(is, "utf-8"));
}else{
br = new BufferedReader(new FileReader(FILENAME));
}
String str = "";
while( (str = br.readLine()) != null) {
System.out.println(str);
}
is.close();
br.close();以上代码仅供参考。未经过严格测试,仅在 Windows 记事本保存的 UTF-8 和 ANSI 格式下测试有效。
确实好用,不过新的问题出现了这个是针对windows下保存的记事本可以用,可是目前我是将Stream保存到txt了,保存后,点击另存为,确实看到此txt是“utf8”的,但是这种文件开头就不符合标准,看来我是不是必须要研究怎么去判断这个stream是否为utf8编码了,而不能去判断txt文件?在帮帮我吧。谢谢大家了。分不够我可以在加。
windows 记事本加入 FEBB 等,只是记事本的一个设计上的约定,是TXT的格式规范,与UFT-8无关。
而从IO流里是没法区分编码的,因为流里都是0101交替,无法判断具体涵义。如果要区分出来,必须要在流两边定一个协议,是用HTTP,还是FTP,还是TXT格式协议,而对于每一种协议,都会有一个或几个字段来区分编码的。
因此,楼主应该研究一下,这个手机是使用的哪种协议,看这种协议是使用默认编码,还是指定编码~