1

直接来自这个oracle 教程,它有点解释如何在 java 中使用随机访问功能。片段如下:

String s = "I was here!\n";
byte data[] = s.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);

ByteBuffer copy = ByteBuffer.allocate(12);

try (FileChannel fc = (FileChannel.open(file, READ, WRITE))) {
    // Read the first 12
    // bytes of the file.
    int nread;
    do {
        nread = fc.read(copy);
    } while (nread != -1 && copy.hasRemaining());

    // Write "I was here!" at the beginning of the file.
    fc.position(0);
    while (out.hasRemaining())
        fc.write(out);
    out.rewind();

    // Move to the end of the file.  Copy the first 12 bytes to
    // the end of the file.  Then write "I was here!" again.
    long length = fc.size();
    fc.position(length-1);
    copy.flip();
    while (copy.hasRemaining())
        fc.write(copy);
    while (out.hasRemaining())
        fc.write(out);
} catch (IOException x) {
    System.out.println("I/O Exception: " + x);
}

我已经在有无存在的情况下测试了这段代码,ByteBuffer copy = ByteBuffer.allocate(12);两种方式的结果都是相同的。有人看到ByteBuffer copy = ByteBuffer.allocate(12);在这个片段中使用有什么用吗?提前致谢。

4

1 回答 1

1

代码测试的结果取决于您用来测试它的文件。但是,只有当文件为空时,您才能在使用/不使用复制字节缓冲区的情况下看到相同的结果。

ByteBuffer 复制 = ByteBuffer.allocate(12);

此行简单地初始化用于临时存储副本的 ByteBuffer,最多为文件内容的前 12 个字节。

于 2013-05-10T14:31:29.177 回答