Date: 2012oct17
Update: 2025oct14
Language: Java
Q. Java: How to write a "touch" in Java
A. Our touch() function is at the bottom of this page. It uses
a few helper functions in this full example:
import java.io.File;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.OutputStream;
class Demo {
private static boolean setModifyTimeNow(final String filename) {
File file = new File(filename);
return file.setLastModified(System.currentTimeMillis());
}
private static boolean makeEmptyFile(final String filename) {
try {
OutputStream out = new FileOutputStream(new File(filename));
out.close();
return true;
}
catch (IOException ex) {
System.err.println("Could not make empty file because " + ex.getMessage());
return false;
}
}
private static boolean isExists(final String filename) {
if (filename == null) return false;
File file = new File(filename);
return file.exists();
}
public static boolean touch(final String filename) {
System.out.println("touch: " + filename);
if (isExists(filename)) {
System.out.println("touch: Already exits so just updating modtime");
return setModifyTimeNow(filename);
}
else {
System.out.println("touch: Doesn't exist so creating");
return makeEmptyFile(filename);
}
}
public static final void main(String[] args) {
boolean result = touch("example.txt");
System.out.println("main: result=" + result);
}
}
Output:
touch: example.txt
touch: Doesn't exist so creating
main: result=true