java.nio.file.FileSystemNotFoundException when getting file from resources folder

前端 未结 5 1766
野的像风
野的像风 2021-01-04 11:58

I am getting this error on the following code (note that this does not happen on my local machine, only on my build server):

Files.readAllBytes(Paths.get(get         


        
5条回答
  •  盖世英雄少女心
    2021-01-04 12:15

    If you use Spring, inject resources. Be it a file, or folder, or even multiple files, there are chances, you can do it via injection. Warning: DO NOT use File and Files.walk with the injected resources, otherwise you'll get FileSystemNotFoundException when running as JAR.

    This example demonstrates the injection of multiple images located in static/img folder.

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.io.Resource;
    import org.springframework.stereotype.Service;
    import javax.annotation.PostConstruct;
    
    @Service
    public class StackoverflowService {
    
        @Value("classpath:static/img/*")
        private Resource[] resources;
        private List filenames;
    
        @PostConstruct
        void init() {
            final Predicate isJPG = path -> path.endsWith(".jpg");
            final Predicate isPNG = path -> path.endsWith(".png");
    
            // iterate resources, filter by type and get filenames
            filenames = Arrays.stream(resources)
                    .map(Resource::getFilename)
                    .filter(isJPG.or(isPNG))
                    .collect(Collectors.toList());
        }
    }
    

提交回复
热议问题