问题
I have a JSF application with the below file structure:
ReportGeneratorJSF
|-- src
| `-- Abc.java
|-- WebContent
| `-- FormattedExcel
| `-- abc.xls
:
In my Abc
class I need to refer the Excel file as
File file = new File("location of abc.xls");
However, whatever path I try, it comes as null
. How do I figure out the right path?
回答1:
The java.io.File
works directly on local disk file system and has absolutely no utter idea about the Java (EE) application context it is running on. So it does absolutely not know that the application "root" is located in C:/some/path/to/ReportGeneratorJSF
. It would assume every relative path to be relative to the "Current Working Directory", i.e. the directory which was currently opened when the Java Virtual Machine is started.
You should never rely on relative paths in java.io.File
being treated correctly. Period.
Given that you've saved it as a JSF webapp resource in the project's webcontent folder, you should instead be using ExternalContext#getResourceAsStream() to get an InputStream
out of it (ultimately, you'd like to create a FileInputStream
out of the File
, right? How else would the File
be useful?). It takes a path relative to the webcontent root instead of the disk file system's current working directory.
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
InputStream input = ec.getResourceAsStream("/FormattedExcel/abc.xls");
// ...
See also:
- getResourceAsStream() vs FileInputStream
来源:https://stackoverflow.com/questions/15971599/how-to-refer-to-a-file-in-webcontent-from-inside-a-java-class-in-src