Problems to access a report in a jar file

大兔子大兔子 提交于 2020-01-23 01:32:05

问题


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?

回答1:


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:

  • http://download.oracle.com/javase/1.4.2/docs/api/java/net/URL.html



回答2:


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();
    }
}


来源:https://stackoverflow.com/questions/4204183/problems-to-access-a-report-in-a-jar-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!