Example of FileTime in Java NIO

By Arvind Rai, December 12, 2013
java.nio.file.attribute.FileTime has been introduced in JDK 7 and is the part of NIO 2. FileTime is the time attribute of a file or directory. FileTime represents a time. FileTime has different methods that can compare to handle time related task. FileTime compares the time form epoch (1970-01-01T00:00:00Z). Find the summary of some important methods and example how to use it.

FileTime.from() in Java NIO

For the given time in any TimeUnit, it returns a FileTime as compared from epoch.

FileTime.toString() in Java NIO

It prints the date, in the format YYYY-MM-DDThh:mm:ss[.s+]Z.

Files.getLastModifiedTime() in Java NIO

It returns the last modified time for a given directory or file as FileTime.

FileTime.to() in Java NIO

It returns the integer. FileTime calculates the time form epoch and returns it in a given TimeUnit.

FileTime.compareTo() in Java NIO

It compares the one file time to another file time to check which file is older.
FileTimeExample.java
package com.concretepage.io.file.attribute;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.concurrent.TimeUnit;
public class FileTimeExample {
	public static void main(String[] args) throws IOException {
		FileTime fileTime1 = FileTime.from(1600, TimeUnit.DAYS);
		System.out.println(fileTime1.toString());
		Path path = Paths.get("D:/cp");
		FileTime fileTime2 = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
		long l = fileTime2.to(TimeUnit.DAYS);
		System.out.println(l);
		int i = fileTime2.compareTo(fileTime1);
		System.out.println(i);
	}
}
 


Output
1974-05-20T00:00:00Z
16045
1
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us