Get a list of resources from classpath directory

前端 未结 14 913
予麋鹿
予麋鹿 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条回答
  •  -上瘾入骨i
    2020-11-22 06:05

    With Spring it's easy. Be it a file, or folder, or even multiple files, there are chances, you can do it via injection.

    This example demonstrates the injection of multiple files located in x/y/z folder.

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.io.Resource;
    import org.springframework.stereotype.Service;
    
    @Service
    public class StackoverflowService {
        @Value("classpath:x/y/z/*")
        private Resource[] resources;
    
        public List getResourceNames() {
            return Arrays.stream(resources)
                    .map(Resource::getFilename)
                    .collect(Collectors.toList());
        }
    }
    

    It does work for resources in the filesystem as well as in JARs.

提交回复
热议问题