kinjal raval
kinjal raval

Reputation: 51

how to get list of all files from folder inside java resources folder

I am having multiple files inside 'protocol' folder. I want to get list of files inside 'protocol' folder which is inside java resources folder (src/main/resources/protocol/...).

so when i tried to access any one file it works fine in eclipse IDE(using main method) and also in wildfly deployment. it gives lines inside files.

List<String> files = IOUtils.readLines(classLoader.getResourceAsStream("protocol/protocol1.csv"));

but when try to read folder it works fine in eclipse IDE(got list of file names) but does not work in wildfly deployment it gives a blank list [].

List<String> files = IOUtils.readLines(classLoader.getResourceAsStream("protocol"));

i am using jboss wildfly server version:9.0.1 and java version "1.8.0_161".

Thanks for any help.

Upvotes: 2

Views: 5552

Answers (2)

kinjal raval
kinjal raval

Reputation: 51

Found solution to fetch all files inside folder.

if we try to access folder by getResource() method it will return in terms of vfs protocol and we need to convert that to

public List<String> loadFiles() throws IOException, Exception {
        List<String> fileNames = new ArrayList<>();
        URL resourceUrl = getClass().getResource("/protocol");
        VirtualJarInputStream jarInputStream = (VirtualJarInputStream) resourceUrl.openStream();
        JarEntry jarEntry = null;
        while ((next = jarInputStream.getNextJarEntry()) != null) {
            fileNames.add(jarEntry.getName());
        }
        return fileNames;
    }

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109547

Something like:

URL url = classLoader.getResourceAsStream("protocol");
Path dirPath = Paths.get(url.toURI());
Stream<Path> paths = Files.list(dirPath);
List<String> names = paths
        .map(p -> p.getFileName().toString())
        .collect(Collectors.toList());

It shows that Path is a more refined generalisation of File. It uses the jar:file: protocol (protocols like http:).

Upvotes: -1

Related Questions