“复制ByteBuffer”在以下代码段中代表什么?

时间:2013-05-10 14:18:34

标签: java io nio

直接来自this 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);的情况下测试了此代码,结果在两个方面都是相同的。 是否有人在此代码段中使用{{1}}有什么用处? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

代码测试的结果取决于您用来测试它的文件。但是,只有当文件为空时,如果使用/不使用复制bytebuffer,您会看到相同的结果。

ByteBuffer copy = ByteBuffer.allocate(12);

此行只是初始化用于临时存储文件内容前12个字节的副本的ByteBuffer。