简体   繁体   English

Java.Random.IO中的ReadLong和WriteLong方法

[英]ReadLong and WriteLong methods in Java.Random.IO

I am trying to write Long using Java command for Random File IO as follows: 我试图使用Java命令针对随机文件IO编写Long,如下所示:

fstreamOut = new FileOutputStream(new File("C:\\Basmah","dataOutput.7"),true);
DataOutputStream out=new DataOutputStream(fstreamOut);
Long p= Long.parseLong(longNumberInString );  // Number of digits for this long key are 7-15
              out.writeLong(p);                  

The problem is that when I write 7-15 digit number using writeLong ; 问题是当我使用writeLong输入7-15位数字时; it writes 8 bytes in file. 它在文件中写入8个字节。 Then I am trying to read the same record into my program and decode it 然后我试图将相同的记录读入我的程序并将其解码

Long l=in.readLong();

but I dont get the same number as I wrote ; 但是我得不到我写的相同的数字; Instead Iget EOF exception. 相反,我得到EOF异常。

A long id 64-bit long. 长id 64位长。 That makes 8 bytes. 这使8个字节。 The DataOutputStream's writeLong method writes the binary representation of the long, not the textual one. DataOutputStream的writeLong方法写入long的二进制表示形式,而不是文本形式的表示形式。 Without knowing the code used to read the long value, it's impossible to tell why it doesn't work. 如果不知道用于读取long值的代码,就无法说出为什么它不起作用。

The code given in your example and comment should work. 您的示例和注释中给出的代码应该可以正常工作。 The fact that it doesn't suggests that something else is going on here: 它并不表示此处正在发生其他事情:

  • Maybe the writing and reading is happening on different files. 也许读写是在不同的文件上进行的。
  • Maybe the file being written is not flushed / closed before you attempt to read it. 在尝试读取文件之前,可能未刷新/关闭正在写入的文件。
  • Maybe something else is overwriting the file. 也许还有其他东西正在覆盖文件。
  • Maybe the snippets of code you have provided are different enough to the real code to make a difference. 也许您提供的代码片段与实际代码足够不同,以至于有所作为。

In the code that attempts to read the file, print what you get when you call f.length() . 在尝试读取文件的代码中,打印调用f.length()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM