Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the last modification time of a Java resource?

Can someone please tell me a reliable way to get the last modification time of a Java resource? The resource can be a file or an entry in a JAR.

like image 242
Aaron Digulla Avatar asked Jan 13 '10 14:01

Aaron Digulla


People also ask

How to get last modified time of a file in Java?

The lastModified() method of the File class returns the last modified time of the file/directory represented by the current File object. You can get the last modified time of a particular file using this method.

Which function is used to get the last modification time?

Using getlastmod() Function: The getlastmod() function is used to get the last modification time of the current page.

How do I find the last modified date of a file?

The File. lastModified read-only property provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.

How do I print the last modified time of a directory?

Using the stat command, we can also control the output by the -c FORMAT option. There are two formats to display the mtime: %y – displays time of last data modification in a human-readable format. %Y – displays time of last data modification in number of seconds since Epoch.


2 Answers

If you with "resource" mean something reachable through Class#getResource or ClassLoader#getResource, you can get the last modified time stamp through the URLConnection:

URL url = Test.class.getResource("/org/jdom/Attribute.class");
System.out.println(new Date(url.openConnection().getLastModified()));

Be aware that getLastModified() returns 0 if last modified is unknown, which unfortunately is impossible to distinguish from a real timestamp reading "January 1st, 1970, 0:00 UTC".

like image 72
jarnbjo Avatar answered Sep 18 '22 16:09

jarnbjo


The problem with url.openConnection().getLastModified() is that getLastModified() on a FileURLConnection creates an InputStream to that file. So you have to call urlConnection.getInputStream().close() after getting last modified date. In contrast JarURLConnection creates the input stream when calling getInputStream().

like image 27
cornz Avatar answered Sep 17 '22 16:09

cornz