我正在閱讀一本關於Java的書,並且我們正在從一個頻道讀入ByteBuffer。我發現作者是構建while循環奇道:爲什麼有人會像這樣構造一個while循環?
try (FileChannel inCh = (FileChannel) Files.newByteChannel(file)) { ByteBuffer lengthBuf = ByteBuffer.allocate(8); int strLength = 0; ByteBuffer[] buffers = { null, ByteBuffer.allocate(8) }; while(true) { if(inCh.read(lengthBuf) == -1) break; lengthBuf.flip(); strLength = (int)lengthBuf.getDouble(); buffers[0] = ByteBuffer.allocate(2*strLength); if(inCh.read(buffers) == -1) { System.err.println("EOF found reading ht eprime string."); break; } System.out.printf("String length: %3s String: %-12s Binary Value: %3d%n", strLength, ((ByteBuffer) (buffers[0].flip())).asCharBuffer().toString(), ((ByteBuffer)buffers[1].flip()).getLong()); lengthBuf.clear(); buffers[1].clear(); } System.out.println("\nEOF reached."); } catch (IOException e) {
我想它是這樣的:
while(inCh.read(lengthBuf) != -1) {
,它的工作原理相同。作者是否會像他那樣寫出實用或代碼清晰的原因?
這可能只是他們的個人喜好。如果您可以證明您的更改以同樣的方式運行,那麼如果您願意,也可以使用該更改。 – Bernard 2013-02-13 01:59:29
不是我能看到的。 – 2013-02-13 02:00:25