问题
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:
- Is this the way to get the path of a report in a jar files?
- 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