Java resource as file

Is there a way in Java to construct a File instance on a resource retrieved from a jar through the classloader?

My application uses some files from the jar (default) or from a filesystem directory specified at runtime (user input). I’m looking for a consistent way of
a) loading these files as a stream
b) listing the files in the user-defined directory or the directory in the jar respectively

Edit: Apparently, the ideal approach would be to stay away from java.io.File altogether. Is there a way to load a directory from the classpath and list its contents (files/entities contained in it)?

Use Excel file as a Resource file for Java Program

Is it possible to Use Excel file as a resource bundle for java program?

Java File release resource

I am using SpringFramework Web MVC and inside the servlet handleRequestInternal, I created a variable to access a file in the local filesystem, i.e. protected ModelAndView handleRequestInternal(HttpSe

How to see if resource file exists in Java?

I am trying to output text to a resource file in Java like so: File file = new File(MLM.class.getClassLoader().getResource(mazes.txt).toString()); BufferedWriter out = new BufferedWriter(new FileWri

play .wav file from jar as resource using java

I want to play a .wav file using java code which is in a jar file as resource. My code is look like this – try { URL defaultSound = getClass().getResource(/images/ads/WindowsNavigationStart.wav); /

How to get Java Resource file into byte[]?

I have a Java program that needs to read a file from a resource within the JAR and it only takes it through byte[]. My problem is converting the resource file from a folder within the project (i.e. to

Clojure: How does clojure.java.io/resource load file?

Could clojure.java.io/resource load file from classpath but outside of the jar file? When I put file within jar file, it’d load file but when I put file outside jar but in classpath it’d not load file

Linux Overwrite Java Resource file

I want to overwrite a quartz-jobs.xml file I have in a WAR deployed in JBOSS under a Linux x86 machine. I have tried several things but I have not been able to obtain the correct path to do it properl

How to load a resource bundle from a file resource in Java?

I have a file called mybundle.txt in c:/temp – c:/temp/mybundle.txt How do I load this file into a java.util.ResourceBundle? The file is a valid resource bundle. This does not seem to work: java.net.U

Accessing a Java Resource as a File

I’m trying to access a resource from the class path/JAR file as a File object. I’m aware that it’s the preferred method to use an InputStream object instead, but I’m using an external library (WorldEd

getting string resource of android project from java file

I am defining a lot of my constant strings in the R.strings resource for my android project. However, i would like to use them in JUST a java file. Where the class is just a java class. Is there anywa

Answers

Try this:

ClassLoader.getResourceAsStream ("some/pkg/resource.properties");

There are more methods available, e.g. see here: http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

ClassLoader.getResourceAsStream and Class.getResourceAsStream are definitely the way to go for loading the resource data. However, I don’t believe there’s any way of “listing” the contents of an element of the classpath.

In some cases this may be simply impossible – for instance, a ClassLoader could generate data on the fly, based on what resource name it’s asked for. If you look at the ClassLoader API (which is basically what the classpath mechanism works through) you’ll see there isn’t anything to do what you want.

If you know you’ve actually got a jar file, you could load that with ZipInputStream to find out what’s available. It will mean you’ll have different code for directories and jar files though.

One alternative, if the files are created separately first, is to include a sort of manifest file containing the list of available resources. Bundle that in the jar file or include it in the file system as a file, and load it before offering the user a choice of resources.

I had the same problem and was able to use the following:

// Load the directory as a resource
URL dir_url = ClassLoader.getSystemResource(dir_path);
// Turn the resource into a File object
File dir = new File(dir_url.toURI());
// List the directory
String files = dir.list()

Here is a bit of code from one of my applications… Let me know if it suits your needs. You can use this if you know the file you want to use.

URL defaultImage = ClassA.class.getResource("/packageA/subPackage/image-name.png");
File imageFile = new File(defaultImage.toURI());

Hope that helps.

A reliable way to construct a File instance on a resource retrieved from a jar is it to copy the resource as a stream into a temporary File (the temp file will be deleted when the JVM exits):

public static File getResourceAsFile(String resourcePath) {
    try {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
        if (in == null) {
            return null;
        }

        File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            //copy stream
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}