Java FileOutputStream写负字节值,写错字节

问题描述 投票:-1回答:1

我遇到了使用FileOutputStream将负字节值写入二进制文件的问题,例如,负字节值。 -1被写入文件,但是它占用了两个字节,在我看来,它们完全是胡说八道。

在我的应用程序中,我在返回byte []的某些对象上具有toByteArray(),因此可以将其写入文件。即使它在许多对象上都“有效”,我还是将对象序列化为存在一些负字节的字节数组(新的byte [] {0,0,0,1,-1,-1,-1,-1, 1、3,-48,-5、10}),当我将该对象写入文件时,负数将被写为“ c0 a2”字节。

测试用例:

public void testWRITE() {
    String fileName = "TEST_FILE.lldb";
    String secondFileName = "SECOND_FILE.lldb";
    FileOutputStream fos;
    FileOutputStream fos2;
    try {
        fos = new FileOutputStream(fileName, false);
        fos2 = new FileOutputStream(secondFileName, false);

        // Writing this to file writes bytes "c2 a0" in place of -1 byte
        FileChannel ch = fos.getChannel();
        ch.position(0);
        ch.write(ByteBuffer.wrap(new byte[] {0, 0, 0, 1, -1, -1, -1, -1, 1, 3, -48, -5, 10}));


        // Writing this to file writes "ff" in of -1 byte
        Pojo pojo = new Pojo();
        FileChannel ch2 = fos2.getChannel();
        ch2.position(0);
        ch2.write(ByteBuffer.wrap(pojo.getBytes()));

        fos.close();
        fos2.close();

    } catch (IOException e) {
        fail();
    }
}

其中Pojo类是简单的POJO,>]

public class Pojo {

    private Integer negativeNumber;

    public Pojo() {
        this.negativeNumber = -1;
    }

    public byte[] getBytes() {
        return Pojo.bytesFromInt(this.negativeNumber);
    }

    public static byte[] bytesFromInt(int value) {
         return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
    }}

[我指望一个事实,当我将一个字节写入文件时,它将只是一个字节,由于它是我图书馆的基石,因此我无法继续进行工作。

错误字节而不是负数Wrong bytes instead of negative numbers

用负整数写序列化的POJO转换为字节数组Writing serialized POJO with negative integer converted to byte array

甚至被认为是FileOutputStream的预期行为吗?我想念什么?

我遇到了使用FileOutputStream将负字节值写入二进制文件的问题,例如,负字节值。 -1被写入文件,但是它占用了两个字节,在我看来它们是...

java serialization fileoutputstream negative-number
1个回答
0
投票

一切都正确书写。

© www.soinside.com 2019 - 2024. All rights reserved.