java

How to Get File Creation Date in Java

In this tutorial, we are going to see how to get file creation date in Java by using java.nio.file.attribute.BasicFileAttributes interface.

  • java.nio.file.attribute.BasicFileAttributes is an interface that was introduced in JDK 7.
  • BasicFileAttributes is part of java NIO 2.
  • BasicFileAttributes provides basic file attributes.
  • To get an instance of BasicFileAttributes, we use Files.readAttributes().
  • BasicFileAttributes can provide last accessed date, last modified date, created date, etc.
[st_adsense]  

Java Program to Get File Creation Date:
import java.nio.file.attribute.*;
import java.nio.file.*;
import java.io.IOException;

public class Main
{
    public static void main(String[] args)
    {
	try {
		Path file = Paths.get("C:\\Users\\PC\\Desktop\\file.txt");
		BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);

		System.out.println("Creation date: " + attr.creationTime());
		System.out.println("Last accessed date: " + attr.lastAccessTime());
		System.out.println("Last modification date: " + attr.lastModifiedTime());
		
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
    }
}

Output:

Creation date: 2022-02-15T22:23:50
Last accessed date: 2022-02-15T14:53:40
Last modification date: 2022-02-20T17:20:44
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *