FileInputStream and FileNotFound Exception

2019-08-21 04:52发布

问题:

I am trying to retrieve a jrxml file in a relative path using the following java code:

 String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
 File report = new File(jasperFileName);
 FileInputStream fis = new FileInputStream(report);

However, most probably I didn't succeed in defining the relative path and get an java.io.FileNotFoundException: error during the execution.

Since I am not so experienced in Java I/O operations, I didn't solve my problem. Any helps or ideas are welcomed.

回答1:

You're trying to treat the jrxml file as an object on the file-system, but that's not applicable inside a web application.

You don't know how or where your application will be deployed, so you can't point a File at it.

Instead you want to use getResourceAsStream from the ServletContext. Something like:

String resourceName = "/WEB-INF/reports/MemberOrderListReport.jrxml"
InputStream is = getServletContext().getResourceAsStream(resourceName);

is what you're after.



回答2:

You should place 'MemberOrderListReport.jrxml' in classpath, such as it being included in a jar placed in web-inf\lib or as a file in web-inf\classes. The you can read the file using the following code:

 InputStream is=YourClass.class.getClassLoader().getResourceAsStream("MemberOrderListReport.jrxml");


回答3:

String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";

Simple. You don't have a /web/WEB-INF/reports/MemoberOrderListReport.jrxml file on your computer.

You are clearly executing in a web-app environment and expecting the system to automatically resolve that in the context of the web-app container. It doesn't. That's what getRealPath() and friends are for.



回答4:

check that your relative base path is that one you think is:

File f = new File("test.txt"); System.out.println(f.getAbsoluteFile());



回答5:

I've seen this kind of problem many times, and the answer is always the same...

The problem is the file path isn't what you think it is. To figure it out, simply add this line after creating the File:

System.out.println(report.getAbsolutePath());

Look at the output and you immediately see what the problem is.