Java Check File Newer 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 utility class of Apache Commons IO library to check the modification date of a given file to determine whether it is newer 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 newer than a specified Date in Java

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

ChekFileNewerDate.java

import org.apache.commons.io.FileUtils;

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

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

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

        System.out.println("File " + file + " newer than " + date + " result is " + result);
    }
}
The output is:
File D:\Data\data.txt newer than Thu May 27 00:28:56 ICT 2021 result is false

How to check a File newer than another File in Java

We also can use the method FileUtils.isFileNewer() to check whether a File is newer than another File or not as below example code.

ChekFileNewerFile.java

import org.apache.commons.io.FileUtils;

import java.io.File;

public class ChekFileNewerFile {
    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.isFileNewer(file1, file2);
        boolean result2 = FileUtils.isFileNewer(file2, file1);

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

Happy Coding 😊