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 :
<pre><span style=' color: Blue;'>import</span> java.io.*; <span style=' color: Blue;'>import</span> java.util.*; <span style=' color: Blue;'>public</span> <span style=' color: Blue;'>class</span> GetDirectoryAndFileModifiedTime{ <span style=' color: Blue;'>public</span> <span style=' color: Blue;'>static</span> <span style=' color: Blue;'>void</span> main(String[] args) <span style=' color: Blue;'>throws</span> IOException{ BufferedReader in = <span style=' color: Blue;'>new</span> BufferedReader(<span style=' color: Blue;'>new</span> InputStreamReader(System.in)); System.out.println("Enter file or directory name in proper format to get the modification date and time : "); File filename = <span style=' color: Blue;'>new</span> File(in.readLine()); <span style=' color: Blue;'>if</span> (filename.isDirectory()){ <span style=' color: Blue;'>if</span> (filename.exists()){ <span style=' color: Blue;'>long</span> t = filename.lastModified(); System.out.println(<span style=' color: Maroon;'>"Directory name : "</span> + filename.getName()); System.out.println("Directory modification date and time : " + <span style=' color: Blue;'>new</span> Date(t)); } <span style=' color: Blue;'>else</span>{ System.out.println(<span style=' color: Maroon;'>"Directory not found!"</span>); System.exit(<span style=' color: Maroon;'>0</span>); } } <span style=' color: Blue;'>else</span>{ <span style=' color: Blue;'>if</span> (filename.exists()){ <span style=' color: Blue;'>long</span> t = filename.lastModified(); System.out.println(<span style=' color: Maroon;'>"File name : "</span> + filename.getName()); System.out.println("File modification date and time : " + <span style=' color: Blue;'>new</span> Date(t)); } <span style=' color: Blue;'>else</span>{ System.out.println(<span style=' color: Maroon;'>"File not found!"</span>); System.exit(<span style=' color: Maroon;'>0</span>); } } } }</pre>
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.
No comments:
Post a Comment