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)
Now both these methods fail at times when the log file is empty (has no content), yet the file size is not zero (2 bytes).
Actually, I think you will find that the file is NOT empty. Rather I think that you will find that those two characters are a CR and a NL; i.e. the file consists of one line that is empty.
If you want to test if a file is either empty or has a single empty line then a simple, relatively efficient way is:
try (BufferedReader br = new BufferedReader(FileReader(fileName))) {
String line = br.readLine();
if (line == null ||
(line.length() == 0 && br.readLine() == null)) {
System.out.println("NO ERRORS!");
} else {
System.out.println("SOME ERRORS!");
}
}
Can we do this more efficiently? Possibly. It depends on how often you have to deal with the three different cases:
You can probably do better by using Files.length() and / or reading just the first two bytes. However, the problems include:
0x0d and 0x0a. (For example ... UTF-16)All of this means that the most efficient possible solution is going to be rather complicated.