1. Introduction
In this article, we are going to show a way to determine file creation time in Java.
2. Read creation time using Files.getAttribute(...)
method from JDK7
From JDK 7 we can determine file creation time using java.nio.Files
class.
Let's check the first approach:
In this example, we make the use of Files.getAttribute(...)
method that takes file Path
and attribute name, which is in this case: creationTime
. The result type depends on the given attribute, so in our example, we need to cast return Object
to FileTime
class that holds timestamp value.
Note that if the filesystem doesn't hold creation time of the files method Files.getAttribute(...)
will return null.
3. Determine file creation time using Files.readAttributes(...)
method
Reading all attributes using Files.readAttributes(...)
method is another way to get file creation time:
In this example we get BasicFileAttributes
using Files.readAttributes(...)
method, and then get the attribute we are looking for: attributes.creationTime()
.
This method is also an operating system dependent. When OS doesn't store file creation times it will return last modified time.
4. Read last modified time using File from java.io
package
In JDK 6 we don't have dedicated API to determine file creation date straightforward. The best we can do here is to get the last modified time. Check the following example:
In this snippet, we create an instance of File
class and use file.lastMofied()
to get modified time as the timestamp.
5. Conclusion
In this article, we've learned how to get the file creation date in Java. We present two approaches from JDK 7 using java.nio.Files
class and one example from JDK 6. Unfortunately below JDK 7 we don't have dedicated API to determine file creation date but we can still get last modified time using old java.io
package.
As always, the code for examples is available over on GitHub.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}