Wednesday 11 March 2020

Get Created date of file in Java

There are multiple ways to get created date of a file.

Approach 1: Using 'Files.getAttribute' method.
//Return creation time in milliseconds
private static long getCreateTime_approach1(String filePath) throws Exception {
 Path path = new File(filePath).toPath();
 FileTime creationTime = (FileTime) Files.getAttribute(path, "creationTime");
 return creationTime.toMillis();
}

Approach 2: Using 'Files.readAttributes' method
//Return creation time in milliseconds
private static long getCreateTime_approach2(String filePath) throws Exception {
 Path path = new File(filePath).toPath();
 BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
 FileTime creationTime = attr.creationTime();
 return creationTime.toMillis();
}

Find the below working application.

App.java
package com.sample.app;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Date;

public class App {

 // Return creation time in milliseconds
 private static long getCreateTime_approach1(String filePath) throws Exception {
  Path path = new File(filePath).toPath();
  FileTime creationTime = (FileTime) Files.getAttribute(path, "creationTime");
  return creationTime.toMillis();
 }

 private static long getCreateTime_approach2(String filePath) throws Exception {
  Path path = new File(filePath).toPath();
  BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
  FileTime creationTime = attr.creationTime();
  return creationTime.toMillis();
 }

 public static void main(String[] args) throws Exception {
  String filePath = "/Users/krishna/Documents/TechnicalDocuments/glob.txt";

  long time1 = getCreateTime_approach1(filePath);
  Date date1 = new Date();
  date1.setTime(time1);

  long time2 = getCreateTime_approach2(filePath);
  Date date2 = new Date();
  date2.setTime(time2);

  System.out.println(date1);
  System.out.println(date2);

 }

}

Output
Mon Sep 09 21:16:30 IST 2019
Mon Sep 09 21:16:30 IST 2019


You may like

No comments:

Post a Comment