How to refer to a file in WebContent from inside a Java class in src [duplicate]

有些话、适合烂在心里 提交于 2021-02-11 10:13:19

问题


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

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