Java Jasper报告在生成jar文件后不起作用
我已经为创建jasper报告编写了以下代码,该代码在NetBeans IDE中运行良好,但在创建该项目的jar文件后,报告不会打开。它也没有显示任何错误 问题是什么 创建jasper报告的代码Java Jasper报告在生成jar文件后不起作用,java,jasper-reports,Java,Jasper Reports,我已经为创建jasper报告编写了以下代码,该代码在NetBeans IDE中运行良好,但在创建该项目的jar文件后,报告不会打开。它也没有显示任何错误 问题是什么 创建jasper报告的代码 //Path to your .jasper file in your package String reportSource = "src/report/Allvendor_personal_info.jrxml"; try { jasperReport = (JasperR
//Path to your .jasper file in your package
String reportSource = "src/report/Allvendor_personal_info.jrxml";
try
{
jasperReport = (JasperReport)
JasperCompileManager.compileReport(reportSource);
jasperPrint = JasperFillManager.fillReport(jasperReport, null, con);
//view report to UI
JasperViewer.viewReport(jasperPrint, false);
con.close();
}
catch(Exception e)
{
JOptionPane.showMessaxgeDialog(null, "Error in genrating report");
}
路径
src
在运行时不存在,您不应该引用它
基于此,Allvendor_personal_info.jrxml
将是一个嵌入式资源,存储在Jar文件中,您将无法像访问普通文件那样访问它,相反,您需要使用Class\getResource
或Class\getresourceastream
String reportSource = "/report/Allvendor_personal_info.jrxml";
InputStream is = null;
try
{
is = getClass().getResourceAsStream(reportSource);
jasperReport = (JasperReport)JasperCompileManager.compileReport(is);
jasperPrint = JasperFillManager.fillReport(jasperReport, null, con);
//...
} finally {
try {
is.close();
} catch (Exception exp) {
}
}
话虽如此,在运行时编译.jrxml
文件应该没有什么理由,相反,您应该在构建时编译这些文件,并部署.jasper
文件。这将提高应用程序的性能,因为即使是基本报告,复杂化过程也不短
这意味着您将使用
jasperReport = (JasperReport) JRLoader.loadObjectFromFile(is);
将环境变量设置为jar文件的lib文件夹,而不是
JasperCompileManager.compileReport
您需要复制包含jasper/Jrxml文件的文件夹,并将其放在jar文件的同一目录中。
每当您编写这样的代码时
String reportSource = "/report/Allvendor_personal_info.jrxml";
//It will look for this file on your location so you need to copy your file on /report/ this location
InputStream is = null;
try
{
is = getClass().getResourceAsStream(reportSource);
jasperReport = (JasperReport)JasperCompileManager.compileReport(is);
jasperPrint = JasperFillManager.fillReport(jasperReport, null, con);
//...
} catch(Exception e){
}
伙计们,我不知道这是否太晚了,但是我在构建了一个Jar可执行文件之后,浪费了一天时间来搜索这个问题的解决方案,关于JasperReport。为了在构建jar后让报表正常工作,只需编写以下几行
String reportUrl = "/reports/billCopyReport.jasper"; //path of your report source.
InputStream reportFile = null;
reportFile = getClass().getResourceAsStream(reportUrl);
Map data = new HashMap(); //In case your report need predefined parameters you'll need to fill this Map
JasperPrint print = JasperFillManager.fillReport(reportFile, data, conection);
JasperViewer Jviewer = new JasperViewer(print, false);
Jviewer.setVisible(true);
/* var conection is a Connection type to let JasperReport connecto to Database, in case you won't use DataBase as DataSource, you should create a EmptyDataSource var*/
路径
src
在运行时将不存在,您不应该引用它。您能告诉我这是什么吗?我也遇到了同样的问题。