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)
FileInputStream fis = new FileInputStream(new File(sLogFilename));
int iByteCount = fis.read();
if (iByteCount == -1)
System.out.println("NO ERRORS!");
else
System.out.println("SOME ERRORS!");
Method 2 (Failure)
File logFile = new File(sLogFilename);
if(logFile.length() == 0)
System.out.println("NO ERRORS!");
else
System.out.println("SOME ERRORS!");
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).
What is the most efficient and accurate method to check if the file is empty? I asked for efficiency, as I have to keep checking the file size thousands of times, in a loop.
Note: The file size would hover around a few to 10 KB only!
Method 3 (Failure)
Following @Cygnusx1's suggestion, I had tried using a FileReader
too, without success. Here's the snippet, if anyone's interested.
Reader reader = new FileReader(sLogFilename);
int readSize = reader.read();
if (readSize == -1)
System.out.println("NO ERRORS!");
else
System.out.println("SOME ERRORS!");
Another way to do this is (using
Apache Commons
FileUtils
) -Check if the first line of file is empty:
You can choose try the FileReader approach but it may not be time to give up just yet. If is the BOM field destroying for you try this solution posted here at stackoverflow.
Byte order mark screws up file reading in Java
Stolen from http://www.coderanch.com/t/279224/Streams/java/Checking-empty-file
Updated: My first answer was premature and contained a bug.
I think the best way is to use
file.length == 0
.It is sometimes possible that the first line is empty.
The idea of your first snippet is right. You probably meant to check
iByteCount == -1
: whether the file has at least one byte: