How to compare with zero byte?

Imagine writing to a file directly at 1025 bytes, leaving the first 1024 bytes at zero.

I want to open the file again and search from the first byte position, check if the first byte is zero (does not have real data)?

+4
source share
3 answers

How would you expect to tell the difference between a file that had 1024 bytes, all written out as zero, and a file that "has no real data"?

If all you want to do is check that the first 1024 bytes are zero, just read the data and compare it in the usual way.

+4
source

What you call a null byte does not match a null reference in Java. The zero byte is usually a byte with all bits, i.e. 0.

So, all you have to do is read the byte and compare it to 0. Note that the read method in InputStream returns int , and -1 means the end of the file.

+3
source

java-byte uses all the values ​​that can be represented by the 8-bit memory in which it is stored, so there is no place for the value of the "invalid" byte by default, and you must choose it yourself (for example, 1 if you use only positive values ) If you need all byte values, you can use a larger data type, such as short, to represent invalid values.

Alternatively, you can independently track free / unused areas in your file, so you need to store information about free and used addresses in your file, but you can still read the write bytes.

0
source

Source: https://habr.com/ru/post/1345216/


All Articles