直接从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);
有什么用处? 在此先感谢。
代码甚至不会编译没有这种说法。 – 2013-05-10 14:20:26
“任何使用ByteBuffer copy = ByteBuffer.allocate(12);' - 而不是* what *?你必须以某种方式初始化它...... – wchargin 2013-05-10 14:21:29
当然,我的意思是没有这个声明和所有那些依赖对象“copy”显然是在删除了构造函数后删除的 – Rollerball 2013-05-10 15:13:29