直接從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