Shpytyack Artem
Shpytyack Artem

Reputation: 306

Non expected bytes with reading file by bytes using Java

I'm trying to read some file by bytes. The problem is that Java shows me not the same bytes, that I can read using Far hex editor.

Read bytes using Far: 00 00 00 17 00 00 00 29 00 00 00 99 00 00 00 9B

Read bytes using Java: 0 0 0 17 0 0 0 29 0 0 0 22 0 0 0 3a

Java code:

while ((line = (byte) _br.read()) != -1) {
    lines.add(line);
    System.out.println("lines = " + Integer.toHexString(line));
}

Upvotes: 2

Views: 173

Answers (1)

user845279
user845279

Reputation: 2804

You are prematurely converting the integer returned by read() to byte. This causes an overflow and could prevent the -1 end of file check from working (on top of your current problem). The documentation it says the value returned is between 0 and 65535 (which can't be handled by a byte variable). In java, byte is signed 8-bit value so you'll have problems whenever a value is greater than 0x7F. Change the line variable type to int and try again.

Upvotes: 1

Related Questions