Search code examples
javaspringjarjasper-reports

Spring Webflux: FileNotFoundException inside my JAR


I am exports PDF usgin jasper reports. In develop, it works fine. But when compile the jar, system throws and FileNotFound Exception for "src/main/resources/reports/myJasperReport.jxml"

When I explore the JAR,I came across that the URL for the report is "/BOOT-INF/classes/resports/myJasperReport.jxml"

I found this link to File inside jar is not visible but didn't solve my problem.

Could you help me please?

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


Solution

  • Add classpath: prefix to your path. And consider the resources folder to be a root.

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

    UPD: Actually, you don't need to get a file at all. Try to get resource as stream:

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