Spring Webflux:我的 JAR 中的 FileNotFoundException

Spring Webflux: FileNotFoundException inside my JAR

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

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

我发现这个 link 到 File inside jar is not visible 但没有解决我的问题。

你能帮帮我吗?

@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());
    }
}

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

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

更新: 实际上,您根本不需要获取文件。尝试以流的形式获取资源:

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