java 如何与空字节进行比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5431364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare to null byte?
提问by nunos
Imagine I am writing to a file directly to the position 1025 bytes, leaving the first 1024 bytes in null.
想象一下,我直接向文件写入 1025 个字节的位置,将前 1024 个字节保留为空。
I want to open the file again, and searching from the first byte position, check if the first byte is null (hasn't real data)?
我想再次打开文件,从第一个字节位置开始搜索,检查第一个字节是否为空(没有真实数据)?
采纳答案by Jon Skeet
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"?
您希望如何区分 1024 个字节全部写为零的文件与“没有真实数据”的文件之间的区别?
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.
如果您只想检查前 1024 个字节是否为零,只需读取数据并以正常方式进行比较。
回答by Laurent Pireyn
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.
你所说的空字节与 Java 中的空引用不同。空字节通常是所有位都清除的字节,即 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.
因此,您所要做的就是读取一个字节并将其与 0 进行比较。请注意, 中的read
方法InputStream
返回一个int
,而 -1 表示文件结束。
回答by josefx
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.
java-byte 使用所有可以由它存储的 8 位内存表示的值,所以没有地方留给默认的“无效”字节值,你必须自己选择一个(例如 -1,如果你仅使用正值)。如果您需要所有字节值,您可以使用更大的数据类型,如 short 来表示无效值。
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.
作为替代方案,您可以自己跟踪文件中的空闲/未使用区域,这样您必须在文件中存储有关空闲和已使用地址的信息,但您仍然可以读取写入字节。