Get a list of resources from classpath directory

前端 未结 14 860
予麋鹿
予麋鹿 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:14

    Custom Scanner

    Implement your own scanner. For example:

    private List<String> getResourceFiles(String path) throws IOException {
        List<String> filenames = new ArrayList<>();
    
        try (
                InputStream in = getResourceAsStream(path);
                BufferedReader br = new BufferedReader(new InputStreamReader(in)))
            String resource;
    
            while ((resource = br.readLine()) != null) {
                filenames.add(resource);
            }
        }
    
        return filenames;
    }
    
    private InputStream getResourceAsStream(String resource) {
        final InputStream in
                = getContextClassLoader().getResourceAsStream(resource);
    
        return in == null ? getClass().getResourceAsStream(resource) : in;
    }
    
    private ClassLoader getContextClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }
    

    Spring Framework

    Use PathMatchingResourcePatternResolver from Spring Framework.

    Ronmamo Reflections

    The other techniques might be slow at runtime for huge CLASSPATH values. A faster solution is to use ronmamo's Reflections API, which precompiles the search at compile time.

    0 讨论(0)
  • 2020-11-22 06:14

    My way, no Spring, used during a unit test:

    URI uri = TestClass.class.getResource("/resources").toURI();
    Path myPath = Paths.get(uri);
    Stream<Path> walk = Files.walk(myPath, 1);
    for (Iterator<Path> it = walk.iterator(); it.hasNext(); ) {
        Path filename = it.next();   
        System.out.println(filename);
    }
    
    0 讨论(0)
提交回复
热议问题