java - FileInputStream.available 会愚弄我吗?

标签 java file-io

这个 FileInputStream.available() javadoc 说:

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.

In some cases, a non-blocking read (or skip) may appear to be blocked when it is merely slow, for example when reading large files over slow networks.

我不确定在这次检查中是否:

if (new FileInputStream(xmlFile).available() == 0)

我可以相信空文件总是返回零吗?

--

感谢@SB,他没有准确回答问题,但第一个给出了最佳选择:

If xmlFile is a java.io.File object, you can use the length() method to get its size.

最佳答案

如果命名文件为空,您可以依靠 new FileInputStream(fileName).available() 返回零。

不能依赖new FileInputStream(fileName).available() == 0 作为文件是否为空的最终测试。如果 fileName 是本地文件系统上的常规文件,它可能会起作用。但是如果 fileName 是一个设备文件或者如果它是一个远程文件系统上的文件,available() 可能会返回零来报告 read() 将不得不阻塞一段时间。 (或者在远程文件系统的情况下,它可能不会。)

测试常规文件长度的更可靠方法是使用 new File(fileName).length() == 0。然而,对于设备文件或管道,length() 调用可能会返回零,而不管最终可以读取的字节数是多少。请记住,如果文件不存在,new File(fileName).length() 也会返回零。

编辑如果您想要一个可靠的测试来查看文件是否为空,您必须进行多次调用:

public static isEmptyFile(String fileName) {
    File file = new File(fileName);
    if (!file.exists()) {
        return false;
    } else if (file.length() != 0L) {
        return false;
    } else if (file.isFile()) {
        return true;
    } else if (file.isDirectory()) {
        return false;
    } else {
        // It may be impossible to tell that a device file / named pipe is
        // "empty" without actually reading it.  This is not a failing of
        // Java: it is a logical consequence of the way that certain
        // devices, etc work.
        throw new CannotAnswerException(...);
    }
}        

但您最好在运行应用程序的所有平台上使用各种"file"类型仔细测试这一点。某些文件谓词的行为被记录为特定于平台的;查看javadoc .

关于java - FileInputStream.available 会愚弄我吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2788869/

相关文章:

java - 文档过滤器在 Java 中不起作用?

java - 从 onvif .wsdl 生成 .java

java - JTextField:将十进制逗号重新映射到点

java - ZXING Android嵌入式IntentIntegrator的使用

java - 打印机在服务器而不是客户端打印

java - 读取jtable中的文件

delphi - 检查文件是否在 Delphi 中打开

java - 即使文件位于目录中,迭代文件也会给出文件未找到异常。你能告诉我为什么吗?谢谢

python - 仅当文件已存在时才追加到文件

c++ - 可移植 VFS 库 C++