如何与空字节比较?
想象一下,我直接写入文件的 1025 字节位置,将前 1024 字节保留为空。
我想再次打开文件,并从第一个字节位置开始搜索,检查第一个字节是否为空(没有真实数据)?
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 real data)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您如何区分 1024 字节全部写为零的文件和“没有实际数据”的文件之间的区别?
如果您只想检查前 1024 个字节是否为零,则只需读取数据并以正常方式进行比较即可。
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.
您所说的空字节与 Java 中的空引用不同。空字节通常是所有位都清零的字节,即 0。
因此您所要做的就是读取一个字节并将其与 0 进行比较。请注意
InputStream
中的read
方法code> 返回一个int
,-1 表示文件结束。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 inInputStream
returns anint
, and -1 means end of file.java 字节使用可以由其存储的 8 位内存表示的所有值,因此没有为默认“无效”字节值留下空间,您必须自己选择一个(例如,如果您选择 -1,则为 -1)。仅使用正值)。如果您需要所有字节值,您可以使用更大的数据类型(例如short)来表示无效值。
作为替代方案,您可以自己跟踪文件中的空闲/未使用区域,这样您就必须在文件中存储有关空闲和已用地址的信息,但您仍然可以读取和写入字节。
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.