简体   繁体   中英

Problems to access a report in a jar file

I have a jar application that contains several reports (files .jasper ) and the way that I get the path of the report is:

getClass().getResource("/reportes/mireporte.jasper").toString();

but when I execute I get the next error: FileNotFoundException although the report is within the jar file when I open it with the winrar.

My questions are:

  1. Is this the way to get the path of a report in a jar files?
  2. Is it possible to open reports that are within of a jar file?

Why are you converting the resource to String ??

Try to use (depending on how you want to use the resource):

  • getResource("/report/mireporte.jasper").getFile()

  • getResource("/report/mireporte.jasper").getInputStream()

Returned object from 'getResource' is URL:

1) Is this the way to get the path of a report in a jar files?

Yes, call the getClass().getClassLoader().getResources("mireporte.jasper") - it will give you a list of resources that matches the name.

2) Is posible to open reports that are within of a jar file?

Yes! Use getClass().getResourceAsStream("...") and read from that one!

Example:

public static void main(String... args) throws IOException {
    final ClassLoader cl = GetResource.class.getClassLoader();

    // print all resources (could be more than one)
    Enumeration<URL> resources =
        cl.getResources("foo/bla/tjo/mireporte.jasper");

    while (resources.hasMoreElements())
        System.out.println(resources.nextElement());


    // read one of the files
    Scanner s = new Scanner(
            cl.getResourceAsStream("foo/bla/tjo/mireporte.jasper"));
    try {
        while (s.hasNextLine()) {
            System.out.println(s.nextLine());
        }
    } finally {
        if (s != null)
            s.close();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM