方法test1用于往“test.a”文件写入整数
@Test
public void test1() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("test.a");
fos.write(7870);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
方法test2用于往“test.a”文件读取数据
@Test
public void test2() {
FileReader fr = null;
try {
fr = new FileReader("test.a");
char[] data = new char[10];
int len;
while ((len = fr.read(data)) != -1) {
for (int i = 0; i < len; i++) {
System.out.println((long) data[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fr != null) {bu
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 结论
- 当写入的整数无法在字符集编码中找到对应的字符时,字符流读取会将其转换成Unicode Character ‘REPLACEMENT CHARACTER’ (U+FFFD):65533
- java中字符流一次到底读几个字节?由于输入的整数找不到对应的字符,故只读1个字节。
fos.write(0xe4);
fos.write(0xbd);
fos.write(0xa0);
如果输入这3个字节
test2中的char[]数组只有一个元素,20320(不强转成long将输出字符“你”)