public static void main(String[] args) {
try {
File f = new File("file.txt");
f.createNewFile();
OutputStream fos = new FileOutputStream(f);
InputStream fis = new FileInputStream(f);
fos.write(200);
System.out.println(fis.read());
} catch (Exception ex) {
Logger.getLogger(MySimple.class.getName()).log(Level.SEVERE, null, ex);
}
}
这将按预期打印200。但是,当我写2000时,它读为208。请解释一下为什么它会以这种方式工作吗?
答案 0 :(得分:2)
方法调用fos.write(200);
写入 byte 数据。当您写入200时,它将保存为8位值。
但是,当您尝试写入2000时,它将忽略前8位之外的任何内容。二进制数字2000是0111 1101 0000
。但是由于丢失了前4位,因此写入的结果值为1101 0000
或十进制的208。
由于write()
接受一个整数值,而read()
返回一个整数值,因此这些方法有点令人困惑。