How to get the file creation date in Java?

This is a basic example of how to get the creation date of a file in Java, using BasicFileAttributes class.

  • First Example:
package com.nourit.javaIO;

package com.nourit.javaIO;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class FileCreationDate {

	public static void main(String[] args) {
		File file = new File("D:/tmp/nourit.txt");
		Path filePath = file.toPath();

		BasicFileAttributes attributes = null;
		try {
			attributes = Files.readAttributes(filePath, BasicFileAttributes.class);
		} catch (IOException exception) {
			System.out.println(exception.getMessage());
		}
		Date creationDate = new Date(attributes.creationTime().to(TimeUnit.MILLISECONDS));

		System.out.println("File " + filePath.toString() + " created " + creationDate);
	}
}
  • Second Example:
package com.nourit.javaIO;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class FileCreationDate1 {

  public static void main(String[] args) throws IOException {
    Path p = Paths.get("D:/tmp/nourit.txt");
    BasicFileAttributes view = Files.getFileAttributeView(p, BasicFileAttributeView.class).readAttributes();
    Date creationDate = new Date(view.creationTime().to(TimeUnit.MILLISECONDS));
    System.out.println("File " + p.toString() + " created " + creationDate);
  }

}

 

Output:

File D:\tmp\nourit.txt created Wed Oct 11 16:36:54 CEST 2017

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*