How to Change the File Date and Time in Java using Commons IO


This example shows how to change / update the date and time of a file. This is done thought the FileUtils class which is part of the Apache Commons IO library.
We can get the actual file time by using the core java.io.File class and calling its lastModified() method which returns the time as a datatype long.
The value is the number of milliseconds elapsed since January 1, 1970. To update the time we use the static touch() method of the FileUtils class which will open and close the file without modifying it, but update the file date and time.
Note that if the file that we are trying to update the time for doesn't exist, it will be created through a call to the touch() method.

The example gets the timestamp for a certain file, calls touch and then gets the timestamp again and print out whether the second timestamp was larger than (i.e. after) the first timestamp.


package com.javadb.examples;

import java.io.IOException;
import org.apache.commons.io.FileUtils;

import java.io.File;

/**
 *
 * @author www.javadb.com
 */

public class Main {

    public static void main(String[] args) {
        try {
            File file = new File("pic.jpg");
            long lastModified1 = file.lastModified();
            FileUtils.touch(file);
            long lastModified2 = file.lastModified();
            System.out.println("File date / time was updated: " + (lastModified2 > lastModified1));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

The output from above is naturally:

File date / time was updated: true

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: