【问题标题】:FileInputStream does not read the correct value?FileInputStream 没有读取正确的值?
【发布时间】:2018-10-15 17:39:02
【问题描述】:
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。请解释一下它为什么会这样?

【问题讨论】:

  • 这个方法只写一个字节。

标签: java fileinputstream fileoutputstream


【解决方案1】:

方法调用fos.write(200); 写入一个字节 的数据。当您写入 200 时,它会将其保存为 8 位值就好了。

但是当您尝试写入 2000 时,它会忽略前 8 位以上的任何内容。二进制的 2000 是0111 1101 0000。但由于前 4 位丢失,写入的结果值为1101 0000 或十进制的 208。

这些方法有点混乱,因为write() 接受一个整数值,而read() 返回一个整数值。

【讨论】:

  • 我认为这可能是因为它忽略了这些位。但是我希望看到 127,因为字节范围在 -127 和 +127 之间
  • @kaka - 你看到了一些奇怪的现象,因为字节被“升级”为一个 int。实际上,它使字节无符号。
猜你喜欢
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 2022-08-11
  • 1970-01-01
  • 2011-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多