java 将 xml 文件存储在资源文件夹 (WAR) 中,从代码中读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2972924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:46:35  来源:igfitidea点击:

Store xml files in resources folder (WAR), read from code

javaresourcesexternalwar

提问by JavaPete

I have different XML-files in my 'src/main/recources' folder, and I'd like to read them from my webapplication.

我的“src/main/resources”文件夹中有不同的 XML 文件,我想从我的 web 应用程序中读取它们。

File f = new File("file1.xml");
f.getAbsolutePath();

The code gets invoked inside a WebService, and this prints out 'C:\Users\Administrator' when I look inside the Tomcat-server-output. My current solution is to put the 'file1.xml'-documents outside of the WAR, in the 'C:\'-folder but this way my WAR is not transferable.

该代码在 WebService 内被调用,当我查看 Tomcat-server-output 时,它会打印出“C:\Users\Administrator”。我当前的解决方案是将 'file1.xml'-documents 放在 WAR 之外的 'C:\'-文件夹中,但这样我的 WAR 就不可转移。

I've also tried

我也试过

    <bean name="webService">
        <property name="document">
         <value>classpath:file1.xml</value>
        </property>
    </bean>

But that just prints out the "classpath:file.xml" without parsing it.

但这只是打印出“classpath:file.xml”而不解析它。

Regards, Pete

问候, 皮特

采纳答案by Adriaan Koster

If you are using the standard maven2 war packaging, your file1.xml is copied to the directory WEB-INF/classes within your warfile.

如果您使用标准的 maven2 war 打包,您的 file1.xml 将被复制到您的 warfile 中的目录 WEB-INF/classes。

You can access this file via the classpath.

您可以通过类路径访问此文件。

URL resourceUrl = URL.class.getResource("/WEB-INF/classes/file1.xml");
File resourceFile = new File(resourceUrl.toURI());

回答by John Topley

If you put the file in a directory underneath WEB-INF (or within WEB-INF itself) then you can read it using the ServletContext's getResourceAsStreammethod:

如果您将文件放在 WEB-INF 下(或 WEB-INF 本身内)的目录中,则可以使用ServletContext'sgetResourceAsStream方法读取它:

try {
  InputStream is = context.getResourceAsStream("/WEB-INF/file1.xml");
  ...
} catch (IOException e) {
  ...
}

回答by techzen

You can put the path info in the properties file that is in the path /WEB-INF/classes - and load this info in the application at runtime.

您可以将路径信息放在路径 /WEB-INF/classes 中的属性文件中 - 并在运行时将此信息加载到应用程序中。

To have different value for this path property you can use the option of maven profiles or any other build tool - so that different environment results in the WAR file having the right properties value for the path suited for that environment.

要为此路径属性设置不同的值,您可以使用 maven 配置文件或任何其他构建工具的选项 - 这样不同的环境会导致 WAR 文件具有适合该环境的路径的正确属性值。