Search code examples
javaiowildfly-9

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.


Solution

  • 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;
        }