Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

10.8. Touching a File

10.8.1. Problem

You need to perform the equivalent of the Unix touch command; you want to create a file or update a file's modified timestamp.

10.8.2. Solution

Use the touch() method from FileUtils. To use touch( ), pass it a File object; if the File does not exist, touch( ) will create a new file. If the file exists, the timestamp of the file will be updated to the current time. The following code demonstrates the touch( ) method on the file testFile.txt:

import org.apache.commons.io.FileUtils;
try {
    File testFile = new File( "testFile.txt" );
    // If testFile didn't already exists, create it
    // If testFile already exists, update the modified timestamp
    FileUtils.touch( testFile );  
} catch( IOException ioe ) {
    System.out.println( "Error touching testFile" );
}

If testFile.txt does not exist, the file will be created by the call to touch( ). If testFile.txt does exist, the last modified timestamp will be updated to the current time after the call to touch( ).


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.