読み取り操作中または後続の呼び出しで EOF に達した場合、read() は -1 を返しますか? Java ドキュメントはこれについて完全に明確ではなく、私が読んでいる本もそうではありません。
本の次のコードは、double、可変長の文字列、バイナリ long の 3 つの異なるタイプの値が繰り返されるファイルを読み取ります。バッファーは、任意の値の中間のランダムな場所で満たされると想定されており、コードはそれを処理します。私が理解していないのは、読み取り操作中に-1 が返された場合、prinf ステートメントで最後の値が出力されないことです。
try(ReadableByteChannel inCh = Files.newByteChannel(ファイル)) {
ByteBuffer buf = ByteBuffer.allocateDirect(256);
buf.position(buf.limit());
int strLength = 0;
byte[] strChars = null;
while(true) {
if(buf.remaining() < 8) {
if(inCh.read(buf.compact()) == -1) {
break;
}
buf.flip();
}
strLength = (int)buf.getDouble();
if (buf.remaining() < 2*strLength) {
if(inCh.read(buf.compact()) == -1) {
System.err.println("EOF found while reading the prime string.");
break;
}
buf.flip();
}
strChars = new byte[2*strLength];
buf.get(strChars);
if(buf.remaining() <8) {
if(inCh.read(buf.compact()) == -1) {
System.err.println("EOF found reading the binary prime value.");
break;
}
buf.flip();
}
System.out.printf("String length: %3s String: %-12s Binary Value: %3d%n",
strLength, ByteBuffer.wrap(strChars).asCharBuffer(), buf.getLong());
}
System.out.println("\n EOF Reached.");