【发布时间】:2012-04-23 13:21:47
【问题描述】:
可能重复:
Most efficient way to check if a file is empty in Java on Windows
如何在 Java 7 中检查文件是否为空?
我使用 ObjectInputStream 中的 available() 方法进行了尝试,但即使文件包含数据,它也始终返回零。
【问题讨论】:
标签: java
可能重复:
Most efficient way to check if a file is empty in Java on Windows
如何在 Java 7 中检查文件是否为空?
我使用 ObjectInputStream 中的 available() 方法进行了尝试,但即使文件包含数据,它也始终返回零。
【问题讨论】:
标签: java
File file = new File("file_path");
System.out.println(file.length());
【讨论】:
System.out.println(Files.size(Paths.get("file_path")));
File file = new File(path);
boolean empty = !file.exists() || file.length() == 0;
可以简写为:
boolean empty = file.length() == 0;
因为根据文档该方法返回
此抽象路径名表示的文件的长度,以字节为单位,如果文件不存在,则为 0L
【讨论】:
empty == false。在我的 sn-p 中,如果文件不存在,第一个条件评估为真,因此文件的长度也没有检查,但结果不同(请记住,这是一个 ||,评估的惰性适用于 @ 987654325@ 和 ||operators)。
file.length() 返回0,这只是为了可读性。
根据 J2RE javadocs:http://docs.oracle.com/javase/7/docs/api/java/io/File.html#length()
public long length()
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.
所以new File("path to your file").length() > 0 应该可以解决问题。抱歉 bd 之前的回答。 :(
【讨论】:
BufferedReader br = new BufferedReader(new FileReader("your_location"));
if (br.readLine()) == null ) {
System.out.println("No errors, and file empty");
}
见Most efficient way to check if a file is empty in Java on Windows
【讨论】:
File file = new File(path);
boolean empty = file.exists() && file.length() == 0;
我要强调的是,如果我们要检查文件是否为空,那么我们必须考虑它是否存在。
【讨论】:
File file = new File("path.txt");
if (file.exists()) {
FileReader fr = new FileReader(file);
if (fr.read() == -1) {
System.out.println("EMPTY");
} else {
System.out.println("NOT EMPTY");
}
} else {
System.out.println("DOES NOT EXISTS");
}
【讨论】: