Why My Java Application can't see the *.jrxml?

2019-01-27 04:31发布

问题:

My project has the following architecture :

My template is "report1.jrxml", then when i excute this code :

  TableModel model = (TableModel) masterTable.getModel();    
  JRTableModelDataSource data = new JRTableModelDataSource(model);
  String reportSource ="report1.jrxml";
  try {
            JasperReport jr = JasperCompileManager.compileReport(reportSource);
            JasperPrint jp = JasperFillManager.fillReport(jr, null,data);
      } catch (JRException ex) 
      {
            Logger.getLogger(master.class.getName()).log(Level.SEVERE, null, ex);
      }

I get this error(I'm sorry for the french language, but is quite understandable :p):

Grave: null
net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: report1.jrxml (Le fichier spécifié est introuvable)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:176)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:156)
    at net.sf.jasperreports.engine.JasperCompileManager.compile(JasperCompileManager.java:171)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:448)
    at testjasper.master.jButton1ActionPerformed(master.java:319)
    at testjasper.master.access$900(master.java:25)
    at testjasper.master$FormListener.actionPerformed(master.java:259)

Netbeans says that the file can't be found , but as you can see in the screenshot, its exists ? How can I solve this "problem" ? rather, what's the problem ? My regards. :p

回答1:

Jasper reports can't see it because the file is an embedded resource (it doesn't exist as a file, but a entry in the Jar file)

You need to get a reference to it by using getClass().getResource("/testjasper/report1.jrxml") which will return a URL.

From memory, you should be able to Jasper a InputStream, this can be achieved by using URL#openConnection