How to check if File is Empty in Java? Example Tutorial

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 the 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. This means you don't need to check if the file exists or not.

Btw, when it comes to deciding the emptiness of a file, some applications might be different than others. For example, some applications 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 the space bar in your file it looks empty but it won't be considered empty by your Java program.

If you have such a requirement then you need to put a special logic that involves reading the file and analyzing content.  Anyway, in this article, I'll explain to you how to check if the 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 the 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 that is not empty. 

By the way, if you are new to Java then I also suggest you join a comprehensive Java course like The Complete Java Masterclass course on Udemy to learn Java in a more structured and guided way. This 80-hour course is the most up-to-date and also very affordable. You can buy in just $10 on Udemy. 





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 EmptyFileCheckerInJava{

  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 the very first time.

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



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 an 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 the file is actually empty, I mean doesn't contain anything. This is also the safe and simplest way to check file size in Java. 


Other Java Tutorials and Articles You may like
  • 21 Tech Skill Java Developers can Learn Today (Skills)
  • 10 Advanced Core Java Courses for Experienced (courses)
  • How to append text to an existing file in Java (tutorial)
  • 10 Free Courses to learn Java in Depth (free courses)
  • How to load CSV files in Java? (tutorial)
  • 20+ Spring Boot Interview Questions with Answers (list)
  • 5 Best Websites to learn Java Online for FREE (websites)
  • 10 Java Frameworks for Full Stack Development (frameworks)
  • 10 Free Courses to learn Fullstack Java (free courses)
  • 15 Spring Data JPA Interview Questions (list)
  • 15 Microservices Interview Questions with Answers (list)
  • 25 Spring Security Interview Questions (answers)
  • How to parse CSV File in Java using Jackson (example)

Thanks for reading this article so far. If you like this Java File empty tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are a complete beginner in Java and looking for a free online course to start learning Java from scratch then I highly recommend you to check out Java Tutorial for Complete Beginners (FREE) course on Udemy. More than 1.2 million people have used this free course to learn Java so far. 

9 comments:

  1. Thank you Paul !

    Your example is very clear and useful. In some
    applications, this problem is really important.
    As usual, your explanation is right to the point
    and we can follow it, because it works.

    Sinatta

    ReplyDelete
    Replies
    1. THank you Sinatta, glad you find this tutorial useful. Please share with your friends and colleagues, it helps a lot.

      Delete
  2. I am happy with your answer. thank you.

    ReplyDelete
  3. Write a java program with the use of regular expression (matcher methods and pattern
    class). The program will ask the student to enter 18RP or 19RP or 20RP to check if his/her
    registration number is existing. If it exists, program will allow the student to enter next
    values (e.g: 3455) and program checks if there is a registration is the same as the one
    entered. If it is, it displays the message “reg_nber exists” otherwise “reg_nber doesn’t
    exist”.

    ReplyDelete
  4. Will this work with these types of Files: xlx, csv, xlsx?

    ReplyDelete
    Replies
    1. Yes, it should work with any type of file but it depends upon what you consider as content. The best thing is that you use their API like Apache POI for Excel files.

      Delete
    2. Thanks, I used apache POI to read Headers.

      Delete

Feel free to comment, ask questions if you have any doubt.