查看文件是否为空
可能重复:
在Windows上检查Java中文件是否为空的最有效方法
如何检查Java 7中的文件是否为空?
我使用ObjectInputStream中的available()方法尝试了它,但即使文件包含数据,它也始终返回零。
File file = new File("file_path"); System.out.println(file.length());
File file = new File(path); boolean empty = !file.exists() || file.length() == 0;
可以缩短为:
boolean empty = file.length() == 0;
因为根据文档,该方法返回
此抽象路径名表示的文件的长度(以字节为单位),如果该文件不存在,则为0L
File file = new File(path); boolean empty = file.exists() && file.length() == 0;
我想强调,如果我们想检查文件是否为空,那么我们必须考虑它是否存在。
BufferedReader br = new BufferedReader(new FileReader("your_location")); if (br.readLine()) == null ) { System.out.println("No errors, and file empty"); }
请参阅最有效的方法来检查Windows上的Java文件是否为空
根据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上一个回答。 🙁
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"); }