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!");
Why not just use:
Is there something wrong with it?
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:
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
and0x0a
. (For example ... UTF-16)All of this means that the most efficient possible solution is going to be rather complicated.
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
Try
FileReader
, this reader is meant to read stream of character, whileFileInputStream
is meant to read raw data.From the Javadoc:
Since you wanna read a log file,
FileReader
is the class to use IMO.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.