I came to a problem with writing negative byte values into binary file using FileOutputStream, where negative byte values, ex. -1 is written into file but it takes there two bytes and they seem to me to be completely nonsense.
In my application I have toByteArray() on some objects returning byte[] so I can write it into a file. Even though it "works" on many objects I got object that gets serialized to byte array where there are some negative bytes (new byte[] {0, 0, 0, 1, -1, -1, -1, -1, 1, 3, -48, -5, 10}) and when I write this object into a file the negative ones are written there as "c0 a2" bytes.
Test case:
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();
}
}
where Pojo class is simple POJO as
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};
}}
As I am counting on a fact that when I write one byte to a file it will be just one byte I can't proceed further with my work as it's a building stone of my library.
Wrong bytes instead of negative numbers
Writing serialized POJO with negative integer converted to byte array
Is that even considered as expected behaviour of FileOutputStream? What am I missing?