这个 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/