Skip to content
Advertisement

Most efficient way to check if a file is empty in Java on Windows

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!");

Advertisement

Answer

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");
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement