-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileCreationDate.java
67 lines (56 loc) · 1.8 KB
/
FileCreationDate.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.javamultiplex.filehandling;
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;
import java.util.Scanner;
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()) {
BasicFileAttributes attributes = Files.readAttributes(file.toPath(), 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) {
String pattern = "^.+\\..+$";
boolean result = false;
if (fileName.matches(pattern)) {
result = true;
}
return result;
}
}