制作jar文件后,Jasper报告无效
我编写了以下用于创建jasper报告的代码,此代码在NetBeans IDE中正常工作,但在创建该项目的jar文件后,报告无法打开。 它也没有显示任何错误。
可能是什么问题?
用于创建jasper报告的代码
//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#getResourceAsStream
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);
而不是JasperCompileManager.compileReport
将环境变量设置为jar文件的lib文件夹
好吧,我不知道是否为时已晚,但是我浪费了一天的时间来搜索这个问题的解决方案,在构建一个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*/
你需要复制具有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){ }