Java: touch – set file last modified time

I just discovered that I need to touch() a file in Java. It appears there isn’t a way to do this using the standard Java library, so I rolled my own:

import java.io.*;
import java.util.Date;

class Touch
{
    /**
     * Touches a given file
     *
     * @author Nick Giles 
     */
    public static void main(String args[])
    {
        try
        {
            // Create a new file object for the file we want to touch
            File f = new File("touch.txt");

            // See if the file already exists
            if (f.exists())
            {
                // The file already exists, so just update its last modified time
                if (!f.setLastModified(System.currentTimeMillis()))
                {
                    throw new IOException("Could not touch file");
                }
            }
            else
            {
                // The file doesn't exist, so create it
                f.createNewFile();
            }
        }
        catch (SecurityException e)
        {
            System.err.println("Security Error: " + e.getMessage());
        }
        catch (IOException e)
        {
            System.err.println("IO Error: " + e.getMessage());
        }
    }
}

Just like the Linux command, if the input is a directory then it will update the last modified time for the directory but not recurse into it. If you need to recurse then the above can easily be extended to recurse itself using f.isDirectory() and f.listFiles(). If anyone needs this then just let me know and I’ll rustle it up, but for now I’ll leave that as en exercise for the reader :-)

This entry was posted in Java and tagged , , , , . Bookmark the permalink.

Leave a Reply

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