How to Check if a File is Empty in Java

In Java, there are several ways to check if a file is empty. Let's explore some of these methods to see which one might be best suited for your needs. 

1. Using the File Class 

The File class provides a straightforward way to ascertain the size of a file using the length() method. If the length is 0, then the file is empty.

import java.io.File;

public class CheckEmptyFile {
    public static void main(String[] args) {
        File file = new File("example.txt");

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

2. Using the NIO Files Class

The Files class, introduced in Java 7, offers a size() method to determine the size of a file, which we can use to check its emptiness.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CheckUsingFilesClass {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");

        try {
            if (Files.size(filePath) == 0) {
                System.out.println("The file is empty.");
            } else {
                System.out.println("The file is not empty.");
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

3. Using BufferedReader 

For text files, we can use a BufferedReader to check if there's content to read. If the first line read is null, the file is empty.

import java.io.BufferedReader;
import java.io.FileReader;

public class CheckUsingBufferedReader {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
            if (br.readLine() == null) {
                System.out.println("The file is empty.");
            } else {
                System.out.println("The file is not empty.");
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

While this method provides insight into the content of text files, it's less efficient for checking large files as it reads the content rather than just checking the file size. 

Conclusion 

Depending on the specific needs and context of your application, you can choose among the methods described above. For a quick check based on file size, the File or Files class methods are recommended. For text-based files where the content might be of interest, the BufferedReader approach can be useful.

Related File Handling Examples

Comments