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

118,689

Solution 1

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

Solution 2

Why not just use:

File file = new File("test.txt");

if (file.length() == 0) {
    // file empty
} else {
    // not empty
}

Is there something wrong with it?

Solution 3

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());
    }        
}

Solution 4

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

Solution 5

Try FileReader, this reader is meant to read stream of character, while FileInputStream is meant to read raw data.

From the Javadoc:

FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.

Since you wanna read a log file, FileReader is the class to use IMO.

Share:
118,689
GPX
Author by

GPX

Updated on July 17, 2022

Comments

  • GPX
    GPX almost 2 years

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