7

This seems like a pretty straightforward question but I haven't been able to find a definitive answer anywhere online. How can I get the date/time a file was created through Java's file manager? Aside from just the name of a file, what else can I get about the file's "properties"?

ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
Brian
  • 7,955
  • 16
  • 66
  • 107
  • Possibly a duplicate of http://stackoverflow.com/questions/2723838/determine-file-creation-date-in-java – jt. Jul 30 '11 at 18:56
  • did you check this, http://stackoverflow.com/questions/32586/how-to-discover-a-files-creation-time-with-java ? – Adisesha Jul 30 '11 at 18:57
  • Hmmm, @jt, I must have overlooked that. You should consider just putting it as your answer, that link pointed me in the right direction. – Brian Jul 30 '11 at 18:59
  • possible duplicate of [How to get creation date of a file in Java](http://stackoverflow.com/questions/741466/how-to-get-creation-date-of-a-file-in-java) – CoolBeans Jul 30 '11 at 18:59
  • @AeroDroid - it will get closed as duplicate. – CoolBeans Jul 30 '11 at 19:00
  • But remember that most Linux filesystems [don't support file creation timestamps](http://en.wikipedia.org/wiki/Comparison_of_file_systems#Metadata). – Mihail Klushnev Nov 28 '13 at 06:30

1 Answers1

11

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).

ColinD
  • 108,630
  • 30
  • 201
  • 202
  • Hmm, well I think I'll go with jt's answer. That worked for me. – Brian Jul 30 '11 at 19:03
  • that seems horrible to return default values like that. Who created this API? What was their reasoning? – Henry Story Oct 16 '13 at 19:20
  • @bblfish: It seems to me that there isn't much potential harm from returning a default value for something like the creation time. It simplifies the API and allows code working with attributes to just treat all `BasicFileAttributes` the same without worrying about whether or not one specific attribute isn't supported by the underlying file system. – ColinD Oct 22 '13 at 20:19
  • Is there a non nio way to get creation time? – ABS Nov 28 '17 at 01:33
  • 1
    @KMP: You can perhaps call a system function like `stat`, but no, not with the `File` API. – ColinD Nov 28 '17 at 17:03