Free Java Utility To Touch Files (Cross Platform)

By Angsuman Chakraborty, Gaea News Network
Saturday, September 23, 2006

This is a simple commandline Java utility which I wrote down in under 5 minutes to help in checking-in (svn commit) over 500 files which were modified but the dates weren’t changed due to an error in our settings. So subversion failed to recognize it. Anyway this simple utility updates the timestamp of any file(s) and directories recursively to current time. It is extremely fast and cross-platform. It does one job and does it well. It is named after the unix utility touch, with similar functionality.

import java.io.File;

/** Super-fast file / directory(recursive) touch.
 *  It doesn't ask for confirmation.
 *  Arguments: File / Directories to touch to current time.
 */
public class Touch {
    public static void main(String ... args) {
        long time = System.currentTimeMillis();
        for(String fileName:args) touch(new File(fileName), time);
    }

    /** Recursively touch file and directories.
     *  @param File (file or directory) for touching.
     */
    public static void touch(File file, long time) {
        if(file.isDirectory()) for(File childFile:file.listFiles()) touch(childFile, time);
        file.setLastModified(time);
    }
}

You can also download the java executable class file. You can run it as follows:
java -classpath . Touch *.html

Replace *.html with file name(s) and directories you want to update. This requires JDK 1.5 or later.

Discussion

Jim
July 2, 2009: 5:39 am

I needed a version that added a delta to each timestamp. Here is what I did:

public class TouchDelta {
public static void main(String[] args) throws Exception {
long delta = Long.valueOf(args[0]); // ms to add
for(int i=1; i<args.length; i++) touchDelta(new File(args[i]), delta);
}

public static void touchDelta(File file, long delta) {
if(file.isDirectory()) for(File childFile:file.listFiles()) touch(childFile, delta);
file.setLastModified(file.lastModified()+delta);
}
}

Enjoy - Jim.


Frieder
November 27, 2007: 1:29 pm

Thanks for this little utility! :)
It would be nice if you could also correct the class file..

July 5, 2007: 8:00 am

Thanks. Corrected.


charles
March 17, 2007: 7:13 am

There’s a problem with the recursinion in the touch method.

This line:
if(file.isDirectory()) for(File childFile:file.listFiles()) touch(file, time);

should be:
if(file.isDirectory()) for(File childFile:file.listFiles()) touch(childFile, time);

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :