0
如果在讀取操作期間或在隨後的調用期間到達EOF,read()是否返回-1? Java文檔在這方面並不完全清楚,我正在閱讀的書也不是。ReadableByteChannel.read()的行爲
本書中的以下代碼正在讀取一個文件,該文件具有三種不同類型的重複值,一個double,一個長度可變的長度和一個二進制長度的字符串。緩衝區應該填充在任何值的中間的隨機位置,代碼將處理它。我不明白的是,如果在讀取操作中-1返回,則最後的值將不會在prinf statment中得到輸出。
try(ReadableByteChannel inCh = Files.newByteChannel(file)) {
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.");
如果是-1在最後一次有效閱讀時返回,您不知道您閱讀了多少數據......似乎答案很不言而喻。 – jtahlborn 2013-02-14 01:06:24