Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a classpath resource, is there a way to get the java.io.File object that has/contains it?

Tags:

java

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.

like image 697
Michael Neale Avatar asked Oct 12 '09 00:10

Michael Neale


People also ask

How do I read a classpath file?

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().

What is classpath resource in Java?

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.


1 Answers

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.

like image 105
Dean Povey Avatar answered Oct 26 '22 02:10

Dean Povey