Skip to content

Instantly share code, notes, and snippets.

@javamultiplex
Created September 25, 2017 13:35
Show Gist options
  • Save javamultiplex/c0c5d060b2fb80f74ef3b7633cdb5f34 to your computer and use it in GitHub Desktop.
Save javamultiplex/c0c5d060b2fb80f74ef3b7633cdb5f34 to your computer and use it in GitHub Desktop.
How to find file creation date of given file in Java?
package com.javamultiplex.filehandling;
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.nio.file.attribute.FileTime;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/**
*
* @author Rohit Agarwal
* @category File handling
* @problem How to get file creation time in Java?
*
*/
public class FileCreationDate {
public static void main(String[] args) throws IOException {
Scanner input = null;
try {
input = new Scanner(System.in);
System.out.println("Enter file name with extension : ");
String fileName = input.nextLine();
if (isValidFileName(fileName)) {
File file = new File(fileName);
if (file.exists()) {
Path path = file.toPath();
BasicFileAttributes attributes = Files.readAttributes(path,BasicFileAttributes.class);
// Getting file creation time.
FileTime time = attributes.creationTime();
String dateTime = getStringFromFileTime(time);
System.out.println("Creation date and time is : " + dateTime);
} else {
System.out.println("File doesn't exist in current directory.");
}
} else {
System.out.println("File name is not valid.");
}
} finally {
if (input != null) {
input.close();
}
}
}
private static String getStringFromFileTime(FileTime time) {
// Getting milliseconds.
long milliseconds = time.toMillis();
Date date = new Date();
// setting milliseconds.
date.setTime(milliseconds);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
// Convert Date to String.
String dateTime = dateFormat.format(date);
return dateTime;
}
private static boolean isValidFileName(String fileName) {
// Regular expression for validating file name.
String pattern = "^.+\\..+$";
boolean result = false;
if (fileName.matches(pattern)) {
result = true;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment