How do I perform a touch on a file?
Author: Deron Eriksson
Description: This Java tutorial describes how to perform a touch on a file using Commons IO.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
The touch() method of the FileUtils class of the ApacheSW Commons IOS library allows us to perform a UNIX-style touch command on a file. If we touch a file that already exists, it updates the 'last modified' time of the file to the current time. If we touch a file that doesn't exist, it creates a blank file with the current time as the 'last modified' time. The Touch class demonstrates this. Touch.javapackage test; import java.io.File; import java.io.IOException; import java.util.Date; import org.apache.commons.io.FileUtils; public class Touch { public static void main(String[] args) throws IOException { File newFile = new File("new-file.txt"); checkFile(newFile); File existingFile = new File("test.txt"); checkFile(existingFile); } public static void checkFile(File file) throws IOException { System.out.println("Checking " + file.getName()); doesFileExist(file); System.out.println("Modified: " + new Date(file.lastModified())); System.out.println("Calling 'touch'"); FileUtils.touch(file); doesFileExist(file); System.out.println("Modified: " + new Date(file.lastModified())); System.out.println(); } public static void doesFileExist(File file) { if (file.exists()) { System.out.println(file.getName() + " exists"); } else { System.out.println(file.getName() + " does not exist"); } } } (Continued on page 2) |