How do I touch a folder with current time using set last modified date & time?

Viewed 1138

I'm trying to update the last modified date of a specific folder, here's what I've got:

public void touchFolder(){
    File folderToTest = new File("C:\\Temp");
    SimpleDateFormat dateFormatUtc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormatUtc.setTimeZone(TimeZone.getTimeZone("UTC"));
    String newTime = dateFormatUtc.format(new Date());
    folderToTest.setLastModified(Long.parseLong(newTime));
}

I am just putting this code in a test case so don't worry about calling this method etc.

I'm getting errors with the parsing that date format as a long, what's the format used in setting the last modified date & time?

3 Answers

This is an example from the documentation, using java.nio.file.Files:

Path path = ...
FileTime now = FileTime.fromMillis(System.currentTimeMillis());
Files.setLastModifiedTime(path, now);

I think you should just do folderToTest.setLastModified(System.currentTimeMillis());

In your code newTime is a formatted date 2018-12-19 15:21:31 which can't be parsed to Long. What you want to do is supply the time in milliseconds e.g.:

Date d = new Date();
file.setLastModified(d.getTime());

As per File.setLastModified() method javadoc:

time - The new last-modified time, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970)

Related