项目resource中文件路径和jar包中文件路径的区别

在这里插入图片描述
打成jar包后,是一个整体的文件。

正常读取

 InputStream inputStream = new FileInputStream("src/main/resources/invoiceTemplate.xlsx");

jar包读取

 InputStream inputStream = this.getClass().getResourceAsStream("/invoiceTemplate.xlsx");

完整代码:

    @GetMapping("/invoiceTemplateDownload2")
    public void templateDownload2(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        InputStream inputStream = this.getClass().getResourceAsStream("/template.xlsx");
        byte[] byteArray = IoUtils.toByteArray(inputStream);
        inputStream.close();
        response.getOutputStream().write(byteArray);
    }

[Java基础] 深入jar包:从jar包中读取资源文件

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐