java - Java中如何使用FileInputStream

标签 java io fileinputstream

我试图理解 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 循环中执行此操作,不断检查可用性?

最佳答案

来自javadoc of available() :

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/

相关文章:

java - 使用绝对路径读取文件时出现 FileNotFoundException

java - 如何比较两个文件是否相同?

java - 使用服务模式和使用独立存储库 Spring Data REST 有什么区别?

java - 如何使用 Gradle 创建可执行 JAR?

haskell - 为什么 Haskell 没有 I Monad(仅用于输入,与 IO monad 不同)?

Java FILE 输入输出和文件输出

java - 如何使用 spring 配置异步和同步事件发布者

多线程和多进程的Java文件锁定方式

io - 使用 F# 读取 MNIST 数据集

java - 让java与C++程序通信