Getting the modification date and time of file or folder in Java

Introduction
In this section, you will learn how to get the last modification date
and time of any file or a folder.
The file name or the directory name is taken by the user to get the last
modification date and time of the specified file or a folder. This program
checks whether the specified file or the folder exists or not.
If the file or the folder exists then the method lastModified(
)
gives you the last modification date and time of the specified file or folder
name. This method shows the time in millisecond.
The getName( ) method retrieves the name of the file or directory.
Here is the code of the program :
import java.io.*;
import java.util.*;
public class GetDirectoryAndFileModifiedTime{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter file or directory name in proper
format to get the modification date and time : ");
File filename = new File(in.readLine());
if (filename.isDirectory()){
if (filename.exists()){
long t = filename.lastModified();
System.out.println("Directory name : " + filename.getName());
System.out.println("Directory
modification date and time : " + new Date(t));
}
else{
System.out.println("Directory not found!");
System.exit(0);
}
}
else{
if (filename.exists()){
long t = filename.lastModified();
System.out.println("File name : " + filename.getName());
System.out.println("File
modification date and time : " + new Date(t));
}
else{
System.out.println("File not found!");
System.exit(0);
}
}
}
}
|
Output of the Program:
C:\nisha>java GetDirectoryAndFileModifiedTime
Enter file or directory name in proper format to get the modification date and time :
myfile.txt
File name : myfile.txt
File modification date and time : Thu Oct 04 16:31:39 GMT+05:30 2007
C:\nisha>
|
Download this example.

|