You can rely on new FileInputStream(fileName).available() , returning zero if the named file is empty.
You cannot rely on new FileInputStream(fileName).available() == 0 as the final test that the file is empty. If fileName is a regular file on the local file system, it will probably work. But if fileName is a device file or if it is a file on a remote file system, available() can return zero to indicate that a read() will need to be blocked for a period. (Or, in the case of the remote file system, this may not be the case.)
A more reliable way to check the length of a regular file is to use new File(fileName).length() == 0 . However, for a device file or channel, a call to length() can return zero, regardless of the number of bytes that can ultimately be read. And keep in mind that new File(fileName).length() also returns zero if the file does not exist.
EDIT If you need a reliable test to find out if a file is empty, you need to make several calls:
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(...); } }
But it would be useful for you to thoroughly test this with various file types on all platforms on which you run your application. The behavior of some file predicates is documented as platform specific; see javadoc .
source share