Java Check File Older than a specified Date or File using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO File Date

In this Java tutorial we learn how to use the FileUtils class of Apache Commons IO library to check the modification date of a given file to determine whether it is older than a specified date or modification date of another file.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.8.0</version>
</dependency>

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

How to check a File older than a specified Date in Java

To check a file’s modification Date older than a specified Date object we can use the method FileUtils.isFileOlder() of Apache Commons IO as the Java program below.

CheckFileOlderDate.java

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Date;

public class CheckFileOlderDate {
    public static void main(String... args) {
        File file = new File("D:\\Data\\data.txt");
        Date date = new Date();

        boolean result = FileUtils.isFileOlder(file, date);

        System.out.println("File " + file + " older than " + date + " result is " + result);
    }
}
The output is:
File D:\Data\data.txt older than Thu May 27 00:25:33 ICT 2021 result is true

How to check a File older than another File in Java

We also can use the method FileUtils.isFileOlder() to compare modification Date of two Files as below example code.

CheckFileOlderFile.java

import org.apache.commons.io.FileUtils;

import java.io.File;

public class CheckFileOlderFile {
    public static void main(String... args) {
        File file1 = new File("D:\\Data\\data.txt");
        File file2 = new File("D:\\Data\\data1.txt");

        boolean result1 = FileUtils.isFileOlder(file1, file2);
        boolean result2 = FileUtils.isFileOlder(file2, file1);

        System.out.println("File " + file1 + " older than file " + file2 + " result is " + result1);
        System.out.println("File " + file2 + " older than file " + file1 + " result is " + result2);
    }
}
The output is:
File D:\Data\data.txt older than file D:\Data\data1.txt result is false
File D:\Data\data1.txt older than file D:\Data\data.txt result is true

Happy Coding 😊