I am trying to check if a log file is empty (meaning no errors) or not, in Java, on Windows. I have tried using 2 methods so far.
Method 1 (Failure)
I combined the two best solutions to cover all the possibilities:
BufferedReader br = new BufferedReader(new FileReader(fileName));
File file = new File(fileName);
if (br.readLine() == null && file.length() == 0)
{
System.out.println("No errors, and file empty");
}
else
{
System.out.println("File contains something");
}
The idea of your first snippet is right. You probably meant to check iByteCount == -1
: whether the file has at least one byte:
if (iByteCount == -1)
System.out.println("NO ERRORS!");
else
System.out.println("SOME ERRORS!");
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());
}
}
Another way to do this is (using Apache Commons
FileUtils
) -
private void printEmptyFileName(final File file) throws IOException {
if (FileUtils.readFileToString(file).trim().isEmpty()) {
System.out.println("File is empty: " + file.getName());
}
}
String line = br.readLine();
String[] splitted = line.split("anySplitCharacter");
if(splitted.length == 0)
//file is empty
else
//file is not empty
I had the same problem with my text file. Although it was empty, the value being returned by the readLine method was not null. Therefore, I tried to assign its value to the String array which I was using to access the splitted attributes of my data. It did work for me. Try this out and tell me if it works for u as well.
I think the best way is to use file.length == 0
.
It is sometimes possible that the first line is empty.