简体   繁体   中英

How to read byte correctly from file using Java RandomAccessFile?

I have a binary file with the byte 88 (which is 136 decimal).

I'm using Java's RandomAccessFile class and the "read" method to read this byte via a pre-defined buffer. I also tried "readUnsignedByte()" but get the same issue as below.

RandomAccessFile randomAccessFile = new RandomAccessFile(inputFile, "r");
byte[] headerBuffer = new byte[32];
randomAccessFile.read(headerBuffer);

The code above gives me -120 for 88, not 136.

I realize that the high-order bit or whatever is set, but I still need to be able to read the file and either get 88 or 136.

The issue is that this byte is the offset into the binary file where I can find the first record so a negative number won't work.

Would appreciate suggestions.

Thanks,

Just do b & 0xFF to convert it to positive integer.

You can use the Byte.toUnsignedInt method to convert a byte into an int in an "unsigned" way.

jshell> byte b = (byte) 0x88;
b ==> -120
jshell> Byte.toUnsignedInt(b);
$57 ==> 136

The operation is the same as b & 0xff but doesn't invoke magic numbers or knowledge about bitwise operators.

Issue with bulk-read

The method read(byte[]) you use for reading multiple bytes at-once actually reads a signed byte as in readByte() . Thus you're right, the first bit represents the sign and will thus be interpreted by Java potentially leading to negative number.

Use offset and read unsigned

Benefit of random-access is to jump to the position/offset in file using seek(long) . So, if you know the exact position of that record-pointer byte, you can jump there and proceed reading the desired byte as unsigned using readUnsignedByte() .

See also

How can I read a file as unsigned bytes in Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM