0

这是我的功能:

// Read a record from the specified RandomAccessFile
   public void read( RandomAccessFile file ) throws IOException    {
      account = file.readInt();
      byte b1[] = new byte[ 15 ];
      file.readFully( b1 );
      firstName = new String( b1, 0 );
      firstName = firstName.trim();
      byte b2[] = new byte[ 15 ];
      file.readFully( b2 );
      lastName = new String( b2, 0 );
      lastName = lastName.trim();
      balance = file.readDouble();
   }

我必须能够从随机访问文件中读取我的一项考试,并且上面的代码有点令人困惑。

这就是我猜正在发生的事情,如果我错了,如果你能纠正我,将不胜感激。

我们从文件file中取出并readInt分配给account. 接下来我想我们创建一个大小为 15 的新字节,并将文件中的名字读入字节,然后分配给firstname. 现在这是我不明白的,有什么作用readFully?以及上面的代码如何知道转移到lastName. 所以简单地说,

byte b1[] = new byte[ 15 ];
      file.readFully( b1 );
      firstName = new String( b1, 0 );
      firstName = firstName.trim();

VS

      byte b2[] = new byte[ 15 ];
      file.readFully( b2 );
      lastName = new String( b2, 0 );
      lastName = lastName.trim();
      balance = file.readDouble();

为什么它不给出相同的值?我们在猜测每个值(名字、姓氏等)有多长?

4

2 回答 2

1

正如 api 所说:

从此文件中读取b.length字节到字节数组中,从当前文件指针开始。此方法从文件中重复读取,直到读取请求的字节数。

    public void write(RandomAccessFile file) throws IOException {
    file.writeInt(account);
    byte b1[] = new byte[15];
    // set firstname to b1
    file.write(b1);
    byte b2[] = new byte[15];
    // set lastname to b2
    file.write(b2);
    double balance =123.1;
    file.writeDouble(balance);
}

如果你生成的文件与上面的完全一样,你阅读进度就可以了。

于 2013-04-04T15:29:40.290 回答
0

If this is a school/university exam, bear in mind that they know to have absurdities on purpose, to confuse you.

Considering a comment from the code you posted:

Read a record from the specified RandomAccessFile

I'd bet that it is defined that the binary file you are reading from has data stored in records like this:

  • account - 4B (size of int)
  • first name - 15B
  • last name - 15B
  • balance - 8B

I also bet that it is supposed that the data is written correctly - meaning exactly in the above order and length. If it is not, e.g. there is a string instead of the integer, or the first name is bigger, it will probably result in error or misinterpreted data - that's why your snippets give different results.

It is a binary file you are reading from anyway, if you want to read something out if it, you must now the exact format in which it was written. Otherwise it's like deciphering an alien letters.

As for the RandomAccessFile.readFullyMethod:

Reads b.length bytes from this file into the byte array, starting at the current file pointer. This method reads repeatedly from the file until the requested number of bytes are read. This method blocks until the requested number of bytes are read, the end of the stream is detected, or an exception is thrown.

于 2013-04-04T15:45:11.200 回答