如何从src中的Java类内部引用WebContent中的文件 [英] How to refer to a file in WebContent from inside a Java class in src
问题描述
我有一个具有以下文件结构的JSF应用程序:
ReportGeneratorJSF
|-- src
| `-- Abc.java
|-- WebContent
| `-- FormattedExcel
| `-- abc.xls
:
在我的Abc
类中,我需要将Excel文件引用为
File file = new File("location of abc.xls");
但是,无论我尝试什么路径,它都以null
出现.如何找出正确的路径?
java.io.File
直接在本地磁盘文件系统上工作,对运行它的Java(EE)应用程序上下文完全一无所知.因此,它绝对不知道应用程序"root"位于C:/some/path/to/ReportGeneratorJSF
中.它将假定每个相对路径都相对于当前工作目录",即Java虚拟机启动时当前打开的目录.
您永远都不应依赖正确对待java.io.File
中的相对路径.时期.
鉴于您已将其另存为项目的webcontent文件夹中的JSF webapp资源,则应改用
I have a JSF application with the below file structure: In my However, whatever path I try, it comes as The You should never rely on relative paths in Given that you've saved it as a JSF webapp resource in the project's webcontent folder, you should instead be using
这篇关于如何从src中的Java类内部引用WebContent中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!另请参见:
ReportGeneratorJSF
|-- src
| `-- Abc.java
|-- WebContent
| `-- FormattedExcel
| `-- abc.xls
:
Abc
class I need to refer the Excel file asFile file = new File("location of abc.xls");
null
. How do I figure out the right path?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.java.io.File
being treated correctly. Period. 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: