2013-05-10 85 views
1

直接从this甲骨文的教程,这是一个有点解释如何在Java中使用随机访问的能力。 代码段如下:“copy ByteBuffer”在下面的代码片段中代表什么?

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);有什么用处? 在此先感谢。

+3

代码甚至不会编译没有这种说法。 – 2013-05-10 14:20:26

+0

“任何使用ByteBuffer copy = ByteBuffer.allocate(12);' - 而不是* what *?你必须以某种方式初始化它...... – wchargin 2013-05-10 14:21:29

+0

当然,我的意思是没有这个声明和所有那些依赖对象“copy”显然是在删除了构造函数后删除的 – Rollerball 2013-05-10 15:13:29

回答

1

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

字节缓冲区复制= ByteBuffer.allocate(12);

这一行简单地初始化字节缓冲区用于一个副本最多暂时存储对前12个字节的文件内容。

+0

实际上没有东西会被复制到那个缓冲区中,检查出来 – Rollerball 2013-05-10 15:14:15

+0

For例如,如果输入文本文件包含“西班牙的雨主要落在飞机上”,则ByteBuffer副本将包含一个警察y的前12个字符:[84,104,101,32,114,97,105,110,32,105,110,32]导致输出“我在这里! 西班牙主要是在计划下我在这里的雨!“ – 2013-05-10 16:15:20