This example shows how to change / update the date and time of a file. This is done thought the FileUtils class which is part of the Apache Commons IO library.
We can get the actual file time by using the core java.io.File class and calling its lastModified() method which returns the time as a datatype long.
The value is the number of milliseconds elapsed since January 1, 1970. To update the time we use the static touch() method of the FileUtils class which will open and close the file without modifying it, but update the file date and time.
Note that if the file that we are trying to update the time for doesn't exist, it will be created through a call to the touch() method.
The example gets the timestamp for a certain file, calls touch and then gets the timestamp again and print out whether the second timestamp was larger than (i.e. after) the first timestamp.
package org.best.examples;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class Main {
public static void main(String[] args) {
try {
File file = new File("pic.jpg");
long lastModified1 = file.lastModified();
FileUtils.touch(file);
long lastModified2 = file.lastModified();
System.out.println("File date / time was updated: " + (lastModified2 > lastModified1));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
We can get the actual file time by using the core java.io.File class and calling its lastModified() method which returns the time as a datatype long.
The value is the number of milliseconds elapsed since January 1, 1970. To update the time we use the static touch() method of the FileUtils class which will open and close the file without modifying it, but update the file date and time.
Note that if the file that we are trying to update the time for doesn't exist, it will be created through a call to the touch() method.
The example gets the timestamp for a certain file, calls touch and then gets the timestamp again and print out whether the second timestamp was larger than (i.e. after) the first timestamp.
package org.best.examples;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class Main {
public static void main(String[] args) {
try {
File file = new File("pic.jpg");
long lastModified1 = file.lastModified();
FileUtils.touch(file);
long lastModified2 = file.lastModified();
System.out.println("File date / time was updated: " + (lastModified2 > lastModified1));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
No comments:
Post a Comment