开发者

How to compare to null byte?

Imagine I am writing to a file directly to the position 1025 bytes, leaving the first 1024 bytes in null.

I want to open the file again, and searching from the first byte position, check if the first byte is null (hasn't re开发者_运维知识库al data)?


How would you expect to tell the difference between a file which had 1024 bytes all written out as zero, and a file which "hasn't real data"?

If all you want to do is check for the first 1024 bytes being zero, just read the data and compare it in the normal way.


What you call a null byte is not the same as a null reference in Java. A null byte is typically a byte with all bits clear, i.e. 0.

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


A java-byte uses all values which can be represented by the 8-bits of memory it is stored in so there is no place left for a default "invalid" byte value and you have to select one yourself (for example -1 if you only use positive values). If you need all byte values you can use a larger data-type like short to represent invalid values.

As an alternative you can keep track of free/unused areas in your file yourself, this way you have to store information about free and used addresses in your file but you can still read an write bytes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜