Learn to get the creation date and time of a file in Java using Java NIO APIs. This may be useful to compare timestamps of files before deleting the older files permanently.
1. File Attributes
The essential file attributes that we can read for a file are listed below. Note that some attributes may not be available in specific operating systems, and returned value will be JVM implementation-specific.
We may get
UnsupportedOperationException if an attribute of the given type is not supported.
2. Using Files.getAttribute()
getAttributes() retrieves the creation date and time of a file using the file attribute name
Path filePath = Paths.get("c:/temp/data.txt"); FileTime creationTime = (FileTime) Files.getAttribute(filePath, "creationTime");
3. Using Files.readAttributes()
readAttributes() method reads a file’s attributes as a bulk operation. It takes the file path and class type of the file attributes. For example,
- BasicFileAttributes: represents the basic attributes associated with a file in a filesystem.
- DosFileAttributes: represents file attributes in platforms like DOS and Samba.
- PosixFileAttributes: represents file attributes in UNIX. POSIX supports nine file permissions: read, write, and execute permissions for the file owner, members of the same group, and “everyone else.
BasicFileAttributes fileAttrs = Files.readAttributes(filePath, BasicFileAttributes.class); FileTime fileTime = fileAttrs.creationTime();
4. Converting in Different Time Units
We can use the
FileTime.to(TimeUnit) method to convert the file creation time to another time elapsed since epoch (1970-01-01T00:00:00Z).
long millis = creationTime.to(TimeUnit.MILLISECONDS); long days = creationTime.to(TimeUnit.DAYS);
Similarly, we can also use HOURS, MINUTES, SECONDS, and MICROSECONDS time units.
To support the new Java 8 Date time classes, we can convert the creation time to
Instant as well.
Instant instant = creationTime.toInstant();
This Java tutorial taught us to get the file creation time using the Java NIO’s
Files class and its methods. These APIs were introduced in Java 7, so there was no direct solution to fetch the creation timestamp till Java 6.
Happy Learning !!