有一个1.txt,
里面的内容是:
aa
bb
cc
dd
ee
ff
文件,另存为,选择编码方式是utf-8,另存为2.txt
读取2.txt这个文件的内容的时候,多出来一个"?",不知道为什么?public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
InputStream in=TestFile.class.getResourceAsStream("2.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(in,"UTF-8"));
String line="";
while((line=br.readLine())!=null){
System.out.println(line);
}
in.close();
br.close();
}
/*输出结果是:
?aa
bb
cc
dd
ee
ff
*/
//为什么多出来一个"?"啊?非常不解!
里面的内容是:
aa
bb
cc
dd
ee
ff
文件,另存为,选择编码方式是utf-8,另存为2.txt
读取2.txt这个文件的内容的时候,多出来一个"?",不知道为什么?public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
InputStream in=TestFile.class.getResourceAsStream("2.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(in,"UTF-8"));
String line="";
while((line=br.readLine())!=null){
System.out.println(line);
}
in.close();
br.close();
}
/*输出结果是:
?aa
bb
cc
dd
ee
ff
*/
//为什么多出来一个"?"啊?非常不解!
Unicode的txt前两个字节是ff fe,
Unicode big endian的txt前两个字节是fe ff
UTF-8的txt前三个字节是ef bb bf
ANSI的txt是直接开始内容的。
因此,在读取的时候需要跳过这些标识字符就可以了。
我用UltraEdit打开另存好的utf的txt文件,但是前两个字节是:FF FE,
但是用代码读出来却是:ef bb bf。不知道是不是UltraEdit的问题。
InputStream in=TestFile.class.getResourceAsStream("2.txt");
in.skip(3);//跳过三个字节
BufferedReader br=new BufferedReader(new InputStreamReader(in,"UTF-8"));
这样读出来就没有错了。
也就是说要根据Bom头来判断文件的编码类型,然后选择需要跳过的字节数,就可以正确无误的读出文件的内容
你可以用PilotEdit来查看原文件的HEX编码,PilotEdit显示的是实际的HEX内容不会转换。
http://topic.csdn.net/u/20100405/17/e86b8de1-3e61-4b6c-bb19-bbfe472b5a25.html