Setting file creation timestamp in Java

这一生的挚爱 提交于 2019-11-30 06:43:56
harperska

Here is how you do it in Java 7 with the nio framework:

public void setFileCreationDate(String filePath, Date creationDate) throws IOException{

    BasicFileAttributeView attributes = Files.getFileAttributeView(Paths.get(filePath), BasicFileAttributeView.class);
    FileTime time = FileTime.fromMillis(creationDate.getTime());
    attributes.setTimes(time, time, time);

}

the BasicFileAttributeView.setTimes(FileTime, FileTime, FileTime) method arguments set the last modified time, last accessed time, and creation time respectively.

Starting from Java 7, you can use java.nio.file.Files.setAttribute and the creationTime attribute:

Path p = Paths.get("C:\\Users\\first.last\\test.txt");
try {
    Calendar c = Calendar.getInstance();
    c.set(2010, Calendar.MARCH, 20);
    Files.setAttribute(p, "creationTime", FileTime.fromMillis(c.getTimeInMillis()));
} catch (IOException e) {
    System.err.println("Cannot change the creation time. " + e);
}

Other attributes can be found here:

Name                  Type
-------------------------------
"lastModifiedTime"    FileTime
"lastAccessTime"      FileTime
"creationTime"        FileTime
"size"                Long
"isRegularFile"       Boolean
"isDirectory"         Boolean
"isSymbolicLink"      Boolean
"isOther"             Boolean
"fileKey"             Object

I believe you have the following options:

  1. Find a tool that does this and is callable from the command line. Then you can interact with it from your java code.
  2. The following link from MSDN File Times shows how any tool would be doing it - especially note the functions GetFileTime and SetFileTime.

And here I guess you will be lucky :) Searching for those functions on Google I found a post here on SO. This answer (not the accepted one) to How to Discover a File's Creation Time with Java seems to do exactly what you want using JNA and the methods above. And if it does, then please upvote that answer one more time :)

Please don't mind the title it has a method to set the creation time too. I hope you will manage to get it working.

You should search for java.nio if you are using jdk >= 1.7

You can also try this (worked well for me on Macos Mavericks and get me two different timestamps):

file.setLastModified(created.getTime()); //Older Timestamp
file.setLastModified(updated.getTime()); //Newer Timestamp
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!