Java how to read folder and list files in that folder in jar environment instead of IDE

馋奶兔 提交于 2019-12-03 17:00:34

This is actually a very difficult question, as the ClassLoader has to take account of the fact that you might have another folder called IconResources on the classpath at runtime.

As such, there is no "official" way to list an entire folder from the classpath. The solution I give below is a hack and currently works with the implementation of URLClassLoader. This is subject to change.

If you want to robust approach, you will need to use a classpath scanner. There are many of these in library form, my personal favourite is Reflections, but Spring has one built in and there are many other options.

Onto the hack.

Generally, if you getResourceAsStream on a URLClassLoader then it will return a stream of the resources in that folder, one on each line. The URLClassLoader is the default used by the JRE so this approach should work out of the box, if you're not changing that behaviour.

Assume I have a project with the following classpath structure:

/
    text/
        one.txt
        two.txt

Then running the following code:

final ClassLoader loader = Thread.currentThread().getContextClassLoader();
try(
        final InputStream is = loader.getResourceAsStream("text");
        final InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
        final BufferedReader br = new BufferedReader(isr)) {
    br.lines().forEach(System.out::println);
}

Will print:

one.txt
two.txt

So, in order to get a List<URL> of the resources in that location you could use a method such as:

public static List<URL> getResources(final String path) throws IOException {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try (
            final InputStream is = loader.getResourceAsStream(path);
            final InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
            final BufferedReader br = new BufferedReader(isr)) {
        return br.lines()
                .map(l -> path + "/" + l)
                .map(r -> loader.getResource(r))
                .collect(toList());
    }
}

Now remember, these URL locations are opaque. They cannot be treated as files, as they might be inside a .jar or they might even be at an internet location. So in order to read the contents of the resource, use the appropriate methods on URL:

final URL resource = ...
try(final InputStream is = resource.openStream()) {
    //do stuff
}

You can read contents of a JAR file with JARInputStream

Finally I work it out. I adopt Boris the Spider's answer, and it works well in IDE but break down in exported Jar. Then I change

final InputStream is = loader.getResourceAsStream("text");

to

final InputStream is = loader.getResourceAsStream("./text");

Then it works both in IDE and JAR.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!