我正在阅读一本关于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