Java采用的是Unicode编码
不同编码方式下的值不同
文件的编码方式可能不同
ANSI 是采用本地编码的意思
字符串改变编码:
new String(str.getBytes("iso-8859-1),“UTF-8”);
用FileInputStream 字节流正确读取中文
- 必须了解文本是以哪种编码方式保存字符的
- 使用字节流读取了文本后,再使用对应的编码方式去识别这些数字,得到正确的字符
File f = new File("E:\\project\\j2se\\src\\test.txt");
try (FileInputStream fis = new FileInputStream(f);) {
byte[] all = new byte[(int) f.length()];
fis.read(all);
//文件中读出来的数据是
System.out.println("文件中读出来的数据是:");
for (byte b : all)
{
int i = b&0x000000ff; //只取16进制的后两位
System.out.println(Integer.toHexString(i));
}
System.out.println("把这个数字,放在GBK的棋盘上去:");
String str = new String(all,"GBK");
System.out.println(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileReader
FileReader得到的是字符,所以一定是已经把字节根据某种编码识别成了字符了
而FileReader使用的编码方式是Charset.defaultCharset()的返回值,如果是中文的操作系统,就是GBK
FileReader是不能手动设置编码方式的,为了使用其他的编码方式,只能使用InputStreamReader来代替,像这样:
try (InputStreamReader isr =new InputStreamReader(new FileInputStream(f),Charset.forName(“UTF-8”)));