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

后端 未结 12 1127
南笙
南笙 2020-12-05 04:30

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)

相关标签:
12条回答
  • 2020-12-05 05:20

    I combined the two best solutions to cover all the possibilities:

    BufferedReader br = new BufferedReader(new FileReader(fileName));     
    File file = new File(fileName);
    if (br.readLine() == null && file.length() == 0)
    {
        System.out.println("No errors, and file empty");
    }                
    else
    {
        System.out.println("File contains something");
    }
    
    0 讨论(0)
  • 2020-12-05 05:28

    The idea of your first snippet is right. You probably meant to check iByteCount == -1: whether the file has at least one byte:

    if (iByteCount == -1)  
        System.out.println("NO ERRORS!");
    else
        System.out.println("SOME ERRORS!");
    
    0 讨论(0)
  • 2020-12-05 05:29

    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());
        }        
    }
    
    0 讨论(0)
  • 2020-12-05 05:32

    Another way to do this is (using Apache Commons FileUtils) -

    private void printEmptyFileName(final File file) throws IOException {
        if (FileUtils.readFileToString(file).trim().isEmpty()) {
            System.out.println("File is empty: " + file.getName());
        }        
    }
    
    0 讨论(0)
  • 2020-12-05 05:33
    String line = br.readLine();
    String[] splitted = line.split("anySplitCharacter");
    if(splitted.length == 0)
        //file is empty
    else
        //file is not empty
    

    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.

    0 讨论(0)
  • 2020-12-05 05:35

    I think the best way is to use file.length == 0.

    It is sometimes possible that the first line is empty.

    0 讨论(0)
提交回复
热议问题