Programming Tips - Java: How can I do a "touch" in Java?
Date: 2012oct17
Updated 2025jan9
Language: Java
Code: indented
Q. Java: How can I do a "touch" in Java?
A. Our touch() function is at the bottom of this page. It uses
a few helper functions.
boolean setModifyTimeNow(String filename) {
File file = new File(filename);
return file.setLastModified(System.currentTimeMillis());
}
boolean makeEmptyFile(String filename) {
try {
OutputStream out = new FileOutputStream(new File(filename));
out.close();
return true;
}
catch(IOException e) {
return false;
}
}
boolean isExists(String filename) {
if (filename == null) return false;
File file = new File(filename);
return file.exists();
}
boolean touch(String filename) {
if (isExists(filename)) {
return setModifyTimeNow(filename);
}
else {
return makeEmptyFile(filename);
}
}