欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Springboot打jar包无法读取resource下文件

程序员文章站 2022-05-04 17:30:06
...

记一次springboot项目打jar包无法获取本地资源文件

  • 本地环境
            ClassPathResource resource = new ClassPathResource("templates/xxx.xlsx");    
            InputStream in = resource.getInputStream();
            //下载文件
            downFile("xxx.xlsx",request,response,in);

使用该方法本地测试完全没有问题,结果发现打成jar包后就会提示找不到路径

方案一:

将资源文件放在jar包之外的路径,该方案维护性较差。

方案二:

使用 PathMatchingResourcePatternResolver 来读取文件资源。

      String fileName = URLEncoder.encode("xx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setContentType("application/octet-stream; charset=UTF-8");
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("templates/xx.xlsx");
        Resource resource = resources[0];
        InputStream stream = resource.getInputStream();
        StringBuilder buffer = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len = 0;
        try {
            while ((len = stream.read(bytes)) != -1) {
                response.getOutputStream().write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }