Determine File Creation Date in Java

How to get proper file creation date of file?

As yshavit said, not all operating systems record the date created. However, you should be able to use java.nio.file to determine this information on operating systems that do have this functionality - see the documentation for files.getAttribute - note that BasicFileAttributeView has a field for creationTime.

You can use FileSystems.getDefault(); to determine what FileAttributeViews are supported on the current operating system.

Files.getAttribute(path, "basic:createdAt"); will return a FileTime object with the date the file was created on a system that supports BasicFileAttributeView. You'll have to convert it to a java.util.Date object, but I'll let you figure that out on your own.

Further Reading

  • NIO API for getAttribute()
  • NIO API for BasicFileAttributeView
  • A tutorial for using readAttributes()
  • A comprehensive tutorial on using FileAttributes
  • Another StackOverflow thread on the same topic

How to find file creation date in linux using java?

You can use stat command in Linux to get various date though creation date isn't available.

Instead you can get these 3 dates about a file:

  • Time of last access
  • Time of last modification (content of the file)
  • Time of last change (metadata of file)

EDIT:

For getting creation/modification times of a file in Java (if using JDK 1.7) see: http://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html

As per this document:

A word about time stamps: The set of basic attributes includes three
time stamps: creationTime, lastModifiedTime, and lastAccessTime. Any
of these time stamps might not be supported in a particular
implementation, in which case the corresponding accessor method
returns an implementation-specific value.

Unfortunately Linux/Unix doesn't store file's creation time hence you cannot get it.

PS: If you can use ext4 filesystem then you can get file's creation time in Unix/Linux.

Getting date/time of creation of a file

I'm not sure how you'd get it using Java 6 and below. With Java 7's new file system APIs, it'd look like this:

Path path = ... // the path to the file
BasicFileAttributes attributes =
Files.readAttributes(path, BasicFileAttributes.class);
FileTime creationTime = attributes.creationTime();

As CoolBeans said, not all file systems store the creation time. The BasicFileAttributes Javadoc states:

If the file system implementation does not support a time stamp to indicate the time when the file was created then this method returns an implementation specific default value, typically the last-modified-time or a FileTime representing the epoch (1970-01-01T00:00:00Z).



Related Topics



Leave a reply



Submit