我试图理解 Oreilly 的 Java IO 中的以下代码。它应该从文件中读取并将其写入控制台:
try {
FileInputStream fis = new FileInputStream("README.TXT");
int n;
while ((n = fis.available()) > 0) {
byte[] b = new byte[n];
int result = fis.read(b);
if (result == -1) break;
String s = new String(b);
System.out.print(s);
} // End while
} // End try
catch (IOException e) {System.err.println(e);}
System.out.println();
我的问题是:
available
方法会立即找到可用的最大长度,然后可以调用read
方法将其打印出来。这应该在一次调用内完成,为什么作者在 while
循环中执行此操作,不断检查可用性?
最佳答案
Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.
该流可能会阻塞,直到您读取其中的一部分。因此,您必须每次只阅读可用的内容。调用read
后,流将被解除阻塞。
因此,在下一次迭代时仍然有可用字节,除非到达文件末尾。此时结果
为-1,如the javadoc of read()所述。 :
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.
请注意,通常您不会读取所有可用内容,因为您希望使用合理大小的缓冲区(并重用它们)。在这种情况下,n
将是 Math.min(BUFFER_SIZE, fix.available())
。
关于java - Java中如何使用FileInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14245610/