码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-05-31 00:42:01      阅读:337      评论:0      收藏:0      [点我收藏+]

标签:inf   input   stream   ble   except   pac   程序   time   文件中   

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("未找到文件"); }

  

 

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

标签:inf   input   stream   ble   except   pac   程序   time   文件中   

原文地址:https://www.cnblogs.com/lonecloud/p/9114040.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!