9

So, this question has been asked a million times i believed and I've been reading them for a couple of hours and trying several options given by some people but none of them work for me.

I want to list all the files inside a directory inside the application's JAR, so in IDE this works:

File f = new File(this.getClass().getResource("/resources/").getPath());

for(String s : f.list){
   System.out.println(s);
}

That gives me all the files inside the directory.

Now, i've tried this also:

InputStream in = this.getClass().getClassLoader().getResourceAsStream("resources/");
    InputStreamReader inReader = new InputStreamReader(in);
    Scanner scan = new Scanner(inReader);

    while (scan.hasNext()) {
        String s = scan.next();
        System.out.println("read: " + s);
    }

    System.out.println("END OF LINE");

And from IDE it prints ALL the files in the directory. Outside IDE prints: "END OF LINE".

Now, I can find an entry inside a Jar with this too:

        String s = new File(this.getClass().getResource("").getPath()).getParent().replaceAll("(!|file:\\\\)", "");
        JarFile jar = new JarFile(s);

            JarEntry entry = jar.getJarEntry("resources");

        if (entry != null){
            System.out.println("EXISTS");
            System.out.println(entry.getSize());
        }

That's some horrible coding i had to do to that String.

Anyway... I can't get the list of resources inside the "resources" directory within the Jar... How can I do this???

3 Answers 3

12

There's no way to simply get a filtered list of internal resources without first enumerating over the contents of the Jar file.

Luckily, that's actually not that hard (and luckily for me you've done most of the hardwork).

Basically, once you have a reference to the JarFile, you simple need to ask for its' entries and iterate over that list.

By checking the JarEntry name for the required match (ie resources), you can filter the elements you want...

For example...

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ReadMyResources {

    public static void main(String[] args) {
        new ReadMyResources();
    }

    public ReadMyResources() {
        JarFile jf = null;
        try {            
            String s = new File(this.getClass().getResource("").getPath()).getParent().replaceAll("(!|file:\\\\)", "");
            jf = new JarFile(s);
            
            Enumeration<JarEntry> entries = jf.entries();
            while (entries.hasMoreElements()) {
                JarEntry je = entries.nextElement();
                if (je.getName().startsWith("resources")) {
                    System.out.println(je.getName());
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                jf.close();
            } catch (Exception e) {
            }
        }
    }

}

Caveat

This type of question actually gets asked a bit. Rather then trying to read the contents of the Jar at runtime, it would be better to produce some kind of text file which contained a list of the available resources.

This could be produced by your build process dynamically before the Jar file is created. It would be a much simpler solution to then read this file in (via getClass().getResource(), for example) and then look up each resource list in the text file...IMHO

6
  • Thanks for the answer and the last remark. Ironically, I've arrived to the same solution before coming back here to read the answers. I guess is the best way, then. Also another way would be to create a temporary folder with all the resources that you need to read at run time in a temporary folder.
    – Jh62
    Commented Aug 15, 2013 at 7:32
  • 1
    I would say having the resources as external resources is probably the easier solution. Using the "file list" solution could allow you to actually deploy multiple resources lists (with the same) across multiple Jars. You'd have to merge these, but it would mean you could gain access to resources across multiple Jars without knowing where they are actually stored Commented Aug 15, 2013 at 7:35
  • @MadProgrammer, could you please provide a the link that demonstrates this to list all the files during the build process? Commented Jun 9, 2017 at 3:50
  • @supertonsky That would depend on what build process you're using. Ant can do it, Maven should be able to it, otherwise you'll need to do it by hand Commented Jun 9, 2017 at 4:03
  • @MadProgrammer, maven should be just fine :) Commented Jun 9, 2017 at 4:24
12

For Spring Framework users, have a look at PathMatchingResourcePatternResolver to do something like the following:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:path/to/resource/*.*");

for (Resource resource : resources) {
    InputStream inStream = resource.getInputStream();
    // Do something with the input stream
}
1
  • 2
    So simple and works like a charm! Thanks! This should be the correct answer in my opinion. You don't have to be a Spring user to use this, just take the Spring jar...
    – jhas
    Commented Sep 17, 2018 at 20:37
0

My case was to read a directory inside resources:

resources structure

As my requirement was to transform resource directory to io.File, finally it looked like this:

public static File getResourceDirectory(String resource) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        URL res = classLoader.getResource(resource);
        File fileDirectory;
        if ("jar".equals(res.getProtocol())) {
            InputStream input = classLoader.getResourceAsStream(resource);
            fileDirectory = Files.createTempDir();
            List<String> fileNames = IOUtils.readLines(input, StandardCharsets.UTF_8);
            fileNames.forEach(name -> {
                String fileResourceName = resource + File.separator + name;
                File tempFile = new File(fileDirectory.getPath() + File.pathSeparator + name);
                InputStream fileInput = classLoader.getResourceAsStream(resourceFileName);
                FileUtils.copyInputStreamToFile(fileInput, tempFile);
            });
            fileDirectory.deleteOnExit();
        } else {
            fileDirectory = new File(res.getFile());
        }

        return fileDirectory;
    }

If resources are in jar, we copy it to temp directory that will be deleted on application end. Then calling getResourceDirectory("migrations") returned me io.File directory for further use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.