Reputation: 19468
If I have a resource on a classpath, I can both load it as stream fine, and there is even a URL representation of it. Unfortunately some implementations of the Url do not implement lastModified correctly.
What I would like is to take a path to something in the classpath, and then resolve it to a file that it is in on disk - if it in a jar, then a File pointing to the jar is fine. I can then get the lastModified from the File object instead of the URL, which will be more helpful.
Upvotes: 8
Views: 6072
Reputation: 9446
Roughly speaking:
URL url = this.getClass().getResource(myResource);
String fileName;
if (url.getProtocol().equals("file")) {
fileName = url.getFile();
} else if (url.getProtocol().equals("jar")) {
JarURLConnection jarUrl = (JarURLConnection) url.openConnection();
fileName = jarUrl.getJarFile().getName();
} else {
throw new IllegalArgumentException("Not a file");
}
File file = new File(fileName);
long lastModified = file.lastModified();
Should do what you want. You will need to catch IOException.
Upvotes: 12
Reputation: 75456
No. This can't be done generally because URL can represent resources which are not associated with a file. For example, it can be HTTP, FTP or JNDI etc.
You can check for protocol and create the File yourself if the protocol is file-based, like "file://path", "jar://path!...".
Upvotes: -1