How to get the creation date of a File using Java

A file creation date can be accessed by reading the BasicFileAttributes from the Path:

Call the following method:

BasicFileAttributes attrs = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
FileTime time = attrs.creationTime();		 

Here an example accessing the creation date and time of a file in Java.

The code creates a File Object from the file path; then it reads the Path attributes using Files.readAttributes. The creation date and time can be accessed from there. The time is a FileTime Object, it is converted to a Date and formatted for rendering. The output String is written in the output.

Create the following java file:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileCreationDate {

	public static void main(String[] argv){

	    	File file = new File( "V:/tmp/test.txt" );

		BasicFileAttributes attrs;
		try {
		    attrs = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
		    FileTime time = attrs.creationTime();
		    
		    String pattern = "yyyy-MM-dd HH:mm:ss";
		    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
			
		    String formatted = simpleDateFormat.format( new Date( time.toMillis() ) );

		    System.out.println( "The file creation date and time is: " + formatted );
		} catch (IOException e) {
		    e.printStackTrace();
		}
	}
}

The output will be:

The file creation date and time is: 2017-01-16 16:54:09

References:

java 7 File

Share this article:

Recent Comments