Most efficient way to check if a file is empty in Java on Windows
Why not just use:
File file = new File("test.txt");
if (file.length() == 0) {
// file empty
} else {
// not empty
}
Is there something wrong with it?
This is an improvement of Saik0's answer based on Anwar Shaikh's comment that too big files (above available memory) will throw an exception:
Using Apache Commons FileUtils
private void printEmptyFileName(final File file) throws IOException {
/*Arbitrary big-ish number that definitely is not an empty file*/
int limit = 4096;
if(file.length < limit && FileUtils.readFileToString(file).trim().isEmpty()) {
System.out.println("File is empty: " + file.getName());
}
}
Check if the first line of file is empty:
BufferedReader br = new BufferedReader(new FileReader("path_to_some_file"));
if (br.readLine() == null) {
System.out.println("No errors, and file empty");
}