Share this page 

Touch a file Tag(s): IO


import java.io.File;

public class FileUtils {

  private FileUtils () {}

  public static boolean touch(String file) {
    return touch(new File(file));
  }

  public static boolean touch(File file) {
    if (file.exists()) {
      return file.setLastModified(System.currentTimeMillis());
    }
    return false;
  }

  public static void main(String args[]) throws Exception {
    System.out.println(FileUtils.touch("C:/temp/java-x.pdf"));
    System.out.println(FileUtils.touch(new File("C:/temp/Hello.class")));
    System.out.println(FileUtils.touch(new File("C:/temp/missingfile.pdf")));
  }
}

Another solution is to use Apache Commons IO
import org.apache.commons.io.FileUtils;

...

FileUtils.touch(myFile)
Note that if the given file doesn't exist then it a new empty file is created.
For a Windows batch solution see this HowTo