我遇到了一个问题,使用FileOutputStream将负字节值写入二进制文件,其中负字节值,例如。 -1被写入文件,但它占用了两个字节,在我看来,它们完全是胡说八道。
在我的应用程序中,某些对象具有toByteArray()返回byte [],因此可以将其写入文件。即使它在许多对象上都“有效”,我还是将对象序列化为存在一些负字节的字节数组(新的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,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};
}}
我指望着这样一个事实,当我向文件中写入一个字节将只是一个字节时,由于它是我图书馆的基石,因此我无法继续进行工作。
这是否甚至被视为FileOutputStream的预期行为? 我想念什么?