我正在使用 jasper 报告导出 PDF。在开发中,它工作得很好。但是当编译 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());
}
}
将
classpath:
前缀添加到您的路径中。并将 resources
文件夹视为根文件夹。
ResourceUtils.getFile("classpath:reports/" + reportFileName);
更新: 实际上,您根本不需要获取文件。尝试以流的形式获取资源:
InputStream report = ReportService.class.getClassLoader().getResourceAsStream("reports/" + reportFileName);
JasperReport jasperReport = JasperCompileManager.compileReport(report);
@xavier 请分享您如何解决此错误。我遇到了同样的错误,而且我没有使用绝对路径方法。