我在 Web 应用程序中有一个普通的 java 类,并且想读取文件WEB-INF
夹下的配置文件。WEB-INF/classes
如果文件位于类路径(文件夹)中,我知道访问文件的方式。由于WEB-INF/classes
文件夹用于.class
文件,因此我只想将配置文件保留在WEB-INF
文件夹下。
谁能告诉我如何从我的 java 类中访问它?
我在 Web 应用程序中有一个普通的 java 类,并且想读取文件WEB-INF
夹下的配置文件。WEB-INF/classes
如果文件位于类路径(文件夹)中,我知道访问文件的方式。由于WEB-INF/classes
文件夹用于.class
文件,因此我只想将配置文件保留在WEB-INF
文件夹下。
谁能告诉我如何从我的 java 类中访问它?
ServletContext.getResourceAsStream()将从相对于 WAR 文件根的给定路径加载文件。就像是:
ServletContext ctx;
InputStream configStream = ctx.getResourceAsStream("/WEB-INF/config.properties");
这里的主要问题是您需要访问 servlet 上下文才能执行此操作。您在 servlet 或过滤器中拥有它,但在应用程序中更靠后的非 Web 组件中却没有。你有几个选择:
getRealPath()
您可以使用方法获取 servlet 的绝对路径,ServletContext
然后附加WEB-INF
到您获得的路径。我认为这是非常基本的,可能还有其他一些答案。
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 class
不imports
,这也是好的部分。
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")
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"));
干杯!!
“new FIleInputStream(Utility.class.getClassLoader().getResource(keyFileName).getPath())”对我有用。
这里“Utility”是我的代码调用这一行的类名,“keyFileName”是我需要打开的文件