Get a list of resources from classpath directory

前端 未结 14 1186
予麋鹿
予麋鹿 2020-11-22 05:20

I am looking for a way to get a list of all resource names from a given classpath directory, something like a method List getResourceNames (String direct

14条回答
  •  清歌不尽
    2020-11-22 06:11

    Based on @rob 's information above, I created the implementation which I am releasing to the public domain:

    private static List getClasspathEntriesByPath(String path) throws IOException {
        InputStream is = Main.class.getClassLoader().getResourceAsStream(path);
    
        StringBuilder sb = new StringBuilder();
        while (is.available()>0) {
            byte[] buffer = new byte[1024];
            sb.append(new String(buffer, Charset.defaultCharset()));
        }
    
        return Arrays
                .asList(sb.toString().split("\n"))          // Convert StringBuilder to individual lines
                .stream()                                   // Stream the list
                .filter(line -> line.trim().length()>0)     // Filter out empty lines
                .collect(Collectors.toList());              // Collect remaining lines into a List again
    }
    

    While I would not have expected getResourcesAsStream to work like that on a directory, it really does and it works well.

提交回复
热议问题