如何从src中的Java类内部引用WebContent中的文件 [英] How to refer to a file in WebContent from inside a Java class in src

查看:129
本文介绍了如何从src中的Java类内部引用WebContent中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下文件结构的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:

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?

解决方案

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:

这篇关于如何从src中的Java类内部引用WebContent中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆