Best Way to Check Newer File Java


In java checking that file is newer than another file or older than another file or checking file modification time with some timestamp can be done using FileUtils class of Apache Commons IO Java library is best option as it has all checks and well tested code.

Library Information

Platform information

jdk1.8.0_60, Java 8, Eclipse

Used library Name: Commons IO

Methods used: FileUtils provides six method to compare file modification time. These methods have all required checks and exception handling. For any production grade Java application it is good to use this utility as it will save effort.

//Tests if the specified File is newer than the specified Date.
static boolean    isFileNewer(File file, Date date)

//Tests if the specified File is newer than the reference File.
static boolean    isFileNewer(File file, File reference)

//Tests if the specified File is newer than the specified time reference.
static boolean    isFileNewer(File file, long timeMillis)

//Tests if the specified File is older than the specified Date.
static boolean    isFileOlder(File file, Date date)

//Tests if the specified File is older than the reference File.
static boolean    isFileOlder(File file, File reference)

//Tests if the specified File is older than the specified time reference.
static boolean    isFileOlder(File file, long timeMillis)

Example for comparing file modification time

package org.code4copy;

import java.io.File;
import java.util.Calendar;

import org.apache.commons.io.FileUtils;

public class FileNewerExample {

    private static void checkFiles(){
        File file1 = new File("c:\\example\\1.txt");
        File file2 = new File("c:\\example\\2.txt");
        boolean res = FileUtils.isFileNewer(file1, file2);
        System.out.println("file1 is newser than file2: "+ res);
        
        res = FileUtils.isFileOlder(file1, file2);
        System.out.println("file1 is older than file2: "+ res);
        
        FileUtils.isFileNewer(file2, Calendar.getInstance().getTimeInMillis());
        System.out.println("file2 is older than current time: "+ res);
    }
    public static void main(String[] args){
        checkFiles();
    }
}

Output

file1 is newser than file2: false
file1 is older than file2: true
file2 is older than current time: true

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.