将字节写入文件然后读取会产生不同的字节

Writing bytes to file then reading yields different bytes

我有一个程序需要从文件中读取和写入 RGB 值。但是,我遇到了应用程序问题,我从文件中读回的数据与我写入的数据不同。

节目:

public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream(new File("ASDF.txt"));
    fos.write(0xFF95999F);
    fos.flush();
    fos.close();
    FileInputStream fis = new FileInputStream(new File("ASDF.txt"));
    byte read;
    while((read = (byte) fis.read()) != -1) {
        System.out.print(String.format("%02X ", read));
    }
    fis.close();
}

输出:

9F

一个字节是8位,这意味着它最多可以存储255个(如果有符号则为128个)。当您调用 fos.write(0xFF95999F) 时,它会将其转换为一个字节,这意味着它会去除除最后两个数字(十六进制)以外的所有数字。如果您需要写入多个字节,则需要将整数转换为字节数组。正如 a related SO article 中所建议的那样,类似于

ByteBuffer b = ByteBuffer.allocate(4);
//b.order(ByteOrder.BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN.
b.putInt(0xFF95999F);

byte[] result = b.array();
fos.write(result);
...

应该更适合你。 (为什么 FileOutputStream 采用 int 而不是 byte 我无法回答,但我想这与某些获取列表的 Java 方法(想到 getCookie) return null 而不是相同的愚蠢原因一个空列表...他们现在坚持的过早优化。)