19

我在 Web 应用程序中有一个普通的 java 类,并且想读取文件WEB-INF夹下的配置文件。WEB-INF/classes如果文件位于类路径(文件夹)中,我知道访问文件的方式。由于WEB-INF/classes文件夹用于.class文件,因此我只想将配置文件保留在WEB-INF文件夹下。

谁能告诉我如何从我的 java 类中访问它?

4

4 回答 4

21

ServletContext.getResourceAsStream()将从相对于 WAR 文件根的给定路径加载文件。就像是:

ServletContext ctx;
InputStream configStream = ctx.getResourceAsStream("/WEB-INF/config.properties");

这里的主要问题是您需要访问 servlet 上下文才能执行此操作。您在 servlet 或过滤器中拥有它,但在应用程序中更靠后的非 Web 组件中却没有。你有几个选择:

  • 通过应用程序范围的变量、注入或其他方式,使 servlet 上下文从 Web 层可用于服务层
  • 将资源加载代码放在 web 层,并将其暴露给服务层
  • 在 web 层加载配置,并将其传递给服务层
于 2012-10-14T16:26:43.830 回答
2

getRealPath()您可以使用方法获取 servlet 的绝对路径,ServletContext然后附加WEB-INF到您获得的路径。我认为这是非常基本的,可能还有其他一些答案。

于 2012-10-14T15:56:19.823 回答
1

hey you all care for context related file loading like application context , web.xml ,config and property file

以下是如何加载任何类型的文件下的java文件,WEB-INF但它存储在另一个结构上,如reportFile您的文件或子文件夹的子文件夹report01-

fullpath is = /WEB-INF/reportFile/report01/report.xml,我已经尝试了很多可能性来加载和读取这个 xml 文件......以上都不适合我,但是,这是未来使用的技巧......

In Action or inservice class you know interface implementation classimports,这也是好的部分。

声明你的文件对象

File myClass = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getFile());
System.out.println("Finding calss path first then remove classes from the path "    + myClass.getCanonicalPath().replaceFirst("classes", "")+"reportFIle/report01/reports.xml")

2.通过从上面删除classes并添加您的特定路径来加载路径

File f = new File(myClass.getCanonicalPath().replaceFirst("classes", "")+"reportFile/report01/reports.xml")

然后

你甚至可以使用 xml 解析器解析它或做任何事情

document = docBuilder.parse(new File(myClass.getCanonicalPath().replaceFirst("classes", "")+"reportFile/report01/reports.xml"));

干杯!!

于 2013-12-19T12:02:22.140 回答
1

“new FIleInputStream(Utility.class.getClassLoader().getResource(keyFileName).getPath())”对我有用。

这里“Utility”是我的代码调用这一行的类名,“keyFileName”是我需要打开的文件

于 2014-03-10T11:33:59.397 回答