使用记事本"另存为",可以看到有编码类型选项:
编码类型有: ANSI, Unicode, UTF-8几种,它们的区别在于前面的BOM码(Bytes Of Mark):
Unicode的txt前两个字节是ff fe;
Unicode big endian的txt前两个字节是fe ff;
UTF-8的txt前三个字节是ef bb bf,也可以没有,即没有BOM.
ANSI的txt是直接开始内容的。
还存在更多的编码方式。
在Java当中,可以通过如下方式进行判别:
public static void readFile(String path)
{
try {
File file = new File(path);
FileInputStream input = new FileInputStream(file);
int pre = (input.read() << 8) + input.read();
String code = "US-ASCII";
switch (pre) {
case 0xefbb:
if (input.read() == 0xbf)
{
code = "UTF-8";
}
break;
case 0xfffe:
code = "Unicode";
break;
case 0xfeff:
code = "UTF-16BE";
break;
default:
code = "GBK"; // "US-ASCII"
break;
}
System.out.println("CodeType: " + code);
input.close();
InputStreamReader reader = new InputStreamReader(new FileInputStream(file), code);
BufferedReader bufReader = new BufferedReader(reader);
String line;
while ((line = bufReader.readLine()) != null)
{
System.out.print(line);
}
System.out.println("");
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
简体中文的电脑是GBK编码,用US-ASCII也可。
下面是执行结果:
CodeType: GBKthis is a gbk file.
这是一个GBK文件.
CodeType: Unicode
this is a unicode file.
这是一个UNICODE文件.
CodeType: UTF-8
?this is a utf-8 file.
这是一个UTF-8文件.
UTF-8第一行前面有一个?, 解决方法是简单地选择跳过,解决具体见CSDN博文。
即:
char[] chars = new char[1];
if (code == "UTF-8")
{
bufReader.read();
}
while (bufReader.read(chars, 0, 1) != -1)
{
System.out.print(chars[0]);
}