このOracle Javaチュートリアル から直接:
次のコード スニペットは、newByteChannel メソッドの 1 つを使用して、読み取りと書き込みの両方でファイルを開きます。返される SeekableByteChannel は FileChannel にキャストされます。
これは、私が上で述べたのと同じリンクにある、彼らが話しているスニペットです。
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);
}
したがって、基本的には、FileChannel にキャストされる SeekableByteChannel オブジェクトを返す Files.newByteChannel() メソッドについて話しているのです。まあ、私はこのプロセスを見ていません。それは隠されている/バックグラウンドで実行されている/または他のソースの魔法のようなものですか? 前もって感謝します。