Friday, 9 March 2018

A Simple Example to Check if File is Empty in Java

One of the readers of my blog Javarevisited emailed me yesterday about how to check if a file is empty in Java and that's why I am writing this post to show that using an example. The common approach for checking if a file is empty or not is to first check if the file exists or not and then check if it contains any content, but Java has done that hard work for you. Well, it's pretty easy to check emptiness for a file in Java by using length() method of the java.io.File class. This method returns zero if the file is empty, but the good thing is it also returns zero if the file doesn't exist. Which means you don't need to check if the file exists or not.

Btw, when it comes to deciding the emptiness of file, some application might be different than others. For example, some application may consider a file with just whitespace as empty but some may not.

The length() method will not consider them empty, which means if you just type space bar in your file it looks empty but it won't be considered empty by your Java program.

If you have such requirement then you need to put a special logic which involves reading the file and analyzing content.

Anyway, in this article, I'll explain to you how to check if given file is empty in Java using a sample program. First, we'll without creating a file.

If you remember, File class is used to represent both file and directory in Java but it's nothing but a path. When you say new File("C:\\myfile.txt") it doesn't create a file but a handle to that path. That's why we can create a File object to given path and call its length() method to check if the file is empty or not.

After that, we'll create a new file and verify again, this time also our code should say the file is empty because even though the file exists, there is nothing in it.

In the last step, we'll write something in the file and repeat the process. This time our program should print the file is not empty.

How to check if a file is empty in Java? Example 


Without any further ado, here is our sample Java program to demonstrate how to check if a given file is empty or not.

package tool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 *
 * A simple example to check if file is empty in Java
 */
public class Hello {

  public static void main(String args[]) throws IOException {

    // checking if file is empty
    // if file doesn't exits then also length() method will consider
    // it empty.
    File newFile = new File("cookbook.txt");

    if (newFile.length() == 0) {
      System.out.println("File is empty ...");
    } else {
      System.out.println("File is not empty ...");
    }

    // Now let's create the file
    newFile.createNewFile();

    // let's try again and check if file is still empty
    if (newFile.length() == 0) {
      System.out.println("File is empty after creating it...");
    } else {
      System.out.println("File is not empty after creation...");
    }

    // Now let's write something on the file
    FileWriter writer = new FileWriter(newFile);
    writer.write("Java is best");
    writer.flush();

    // don't forget to close the FileWriter
    writer.close();

    // Now let's check again and verify if file is still empty
    if (newFile.length() == 0) {
      System.out.println("File is still empty after writing into it...");
    } else {
      System.out.println("File is not empty after writing something ...");
    }

  }
}

Output
File is empty ...
File is empty after creating it...
File is not empty after writing something ...

You can clearly see that when we first checked by creating a File object, we got the File is empty because the file didn't even exist. Remember, a file is not created in Java until you call the createNewFile()method.

After that, we checked again but this time also we got the File is empty output because even though the file exists it was actually empty, nothing was written on it.

In the third case, we writing one line "Java is great" on file using FileWriter and then checked again. Boom!!!, this time the file wasn't empty which means our code is working fine as expected.

You can also copy paste this program in your Eclipse IDE and run and it should print the same output very first time.

Oracle Java Tutorials and Materials, Oracle Java Guides, Oracle Java Learning

But, after that, the output will change and it will always print:

File is not empty ...
File is not empty after creation...
File is not empty after writing something ...

Can you guess why?

Well, because after the first run of this program, you should already have a cookbook.txt file in your Eclipse's project directory and it is not empty hence it prints not empty. The createNewFile() method will not override if a file with the same name already exists.

Another thing, which you should keep in mind is calling the flush() or close() method after writing something on file. For example, if you remove the flush() method and check if the file is empty or not, you may receive incorrect result i.e. file is empty, even after you have written something on it.

Can you guess why?

Well, because the content may not be flushed to the file when you checked, that's why calling flush() is important before checking.

That's all about how to check if a file is empty in Java. You can simply call the length() method without worrying about whether the file exists or not. This method returns zero if the file doesn't exist or file is actually empty i.e. doesn't contain anything.

Related Posts