Java Program to Get the Creation Time of a File
Last Updated :
14 Sep, 2021
Use java.nio package for extracting the creation date and time of any file through java. To extract the date and time of the file use BasicFileAttributes class. java.nio package helps us to get the creation time, last access time, and last modified time, it works for both file and directory.
Approach:
- Import the necessary java libraries.
- Store the path of the file whose creation time we want.
- Create the path object and specify the path of the file into it.
- Then we have to create BasicFileAttributes class using the readAttributes() method.
- In readAttributes() method we have to pass two parameters which are path object and BasicFileAttributes class.
- Now we have to just call creationTime() method using attributes.
Below is the implementation to get the creation time of the file:
Java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
public class JavafileCreationTime {
public static void main() throws IOException
{
String filename
= "C:/Users/HARDSOL/Desktop/New folder (2)" ;
File my_file = new File(filename);
Path path = my_file.toPath();
BasicFileAttributes file_att = Files.readAttributes(
path, BasicFileAttributes. class );
System.out.printf( "File Creation Time %s%n " ,
file_att.creationTime());
}
}
|
Output:
Below is the implementation to get the creation time of the file in the SimpleDateFormat:
Java
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.text.SimpleDateFormat;
public class JavafileCreationTimee {
public static void main() throws IOException
{
String filename
= "C:/Users/HARDSOL/Desktop/New folder (2)" ;
File my_file = new File(filename);
Path path = my_file.toPath();
BasicFileAttributes file_att = Files.readAttributes(
path, BasicFileAttributes. class );
SimpleDateFormat sd
= new SimpleDateFormat( "MM/dd/yyyy HH:mm:ss" );
System.out.print( "File Creation Time: " );
System.out.print(
sd.format(file_att.creationTime().toMillis()));
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...