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.
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".
Apache Commons VFS provides a generic way of interacting with files from different sources. FileObject.getContent() returns a FileContent object which has a method for retreiving the last modified time.
Here is a modified example from the VFS website:
import org.apache.commons.vfs.FileSystemManager;
import org.apache.commons.vfs.FileObject;
...
FileSystemManager fsManager = VFS.getManager();
FileObject jarFile = fsManager.resolveFile( "jar:lib/aJarFile.jar" );
System.out.println( jarFile.getName().getBaseName() + " " + jarFile.getContent().getLastModifiedTime() );
}
// List the children of the Jar file
FileObject[] children = jarFile.getChildren();
System.out.println( "Children of " + jarFile.getName().getURI() );
for ( int i = 0; i < children.length; i++ )
{
System.out.println( children[ i ].getName().getBaseName() + " " + children[ i ].getContent().getLastModifiedTime());
}
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().