springboot jar包运行中获取资源文件

1. 今天晚上写了一个程序,基于Spring boot的一个小网站,发现使用FileUtils.class.getResource(path)来获取jar包中的资源文件并不能成功,其路径很奇怪

file:/Users/lonecloud/Documents/ideaCode/git/export/target/export-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/temp/temp.xls

 查阅资料后,并且查看jar包中的资源文件发现有!还有classes!这样的文字,超级奇怪。后面找到一个折中的方法解决了该问题

public static File getJarResourceFile(String path, String fileName){
        //获取容器资源解析器
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            //获取所有匹配的文件
            Resource[] resources = resolver.getResources(path + fileName);
            if (resources.length > 1) {
                //获得文件流,因为在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流
                InputStream stream = resources[0].getInputStream();
                if (logger.isInfoEnabled()) {
                    logger.info("读取的文件流  [" + stream + "]");
                }
                String targetFilePath = System.getProperty("user.home") + File.separator + resources[0].getFilename();
                if (logger.isInfoEnabled()) {
                    logger.info("放置位置  [" + targetFilePath + "]");
                }
                File ttfFile = new File(targetFilePath);
                org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, ttfFile);
                return ttfFile;
            }
        } catch (IOException e) {
            if (logger.isWarnEnabled()) {
                logger.warn("读取文件流失败,写入本地库失败! " + e);
            }
        }
        throw new RuntimeException("未找到文件"); }

  

 

猜你喜欢

转载自www.cnblogs.com/lonecloud/p/9114040.html