首页 > 解决方案 > Spring Webflux:我的 JAR 中的 FileNotFoundException

问题描述

我正在导出 PDF usgin jasper 报告。在开发中,它工作正常。但是在编译 jar 时,系统会抛出“src/main/resources/reports/myJasperReport.jxml”的 FileNotFound 异常

当我探索 JAR 时,我发现报告的 URL 是“/BOOT-INF/classes/resports/myJasperReport.jxml”

我发现这个指向jar 内文件的链接不可见,但没有解决我的问题。

请问你能帮帮我吗?

@Slf4j
@Service
public class ReportService {
    private static final String REPORTS_BASE_PATH = "src/main/resources/reports/";

    public ByteArrayInputStream exportReport(
            String reportFileName,
            Integer idCC,
            Map<String,Object> parameters
    ) throws Exception {
        Connection connection = CustomEntityManagerFactoryPostgresImpl
                .getInstance()
                .getConnection(idCC);

        File file = ResourceUtils.getFile(REPORTS_BASE_PATH + reportFileName);
        JasperReport jasperReport = JasperCompileManager.compileReport(file.getAbsolutePath());
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, connection);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);

        return new ByteArrayInputStream(outputStream.toByteArray());
    }
}

标签: javaspringjarjasper-reports

解决方案


为您的路径添加classpath:前缀。并将resources文件夹视为根目录。

ResourceUtils.getFile("classpath:reports/" + reportFileName);

UPD:实际上,您根本不需要获取文件。尝试将资源作为流获取:

InputStream report = ReportService.class.getClassLoader().getResourceAsStream("reports/" + reportFileName);
JasperReport jasperReport = JasperCompileManager.compileReport(report);

推荐阅读