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.
In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().
ClassPathResource is a Resource implementation for class path resources. It supports resolution as java. io. File if the class path resource resides in the file system, but not for resources in a JAR. To read a file inside a jar or war file, please use resource.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With