【问题标题】:How to specify path to resources inside a war file?如何指定war文件中资源的路径?
【发布时间】:2015-12-04 07:05:05
【问题描述】:

我已经使用文本编辑器使用 maven 和 spring 框架构建了我的项目。 我可以使用终端上的命令在根文件夹中运行项目

mvn spring-boot:run

我已经使用 java 语句在 java 文件中引用了我的源文件

Document doc = builder.parse("src/main/resources/data/resorts.xml");

一切正常。

当我使用命令将整个项目导出为war文件时

mvn package

在终端上

我在根目录的目标文件夹中得到一个war文件

我使用命令运行war文件

java -jar filename.war

没有编译错误,但在运行时显示错误 java.io.FileNotFoundException

我认为我没有正确指定参考文件的路径

您能否提及必须在路径字符串中提及相对路径以使其能够从 war 文件中运行。

我的目录结构是

.
    |-- src
    |   `-- main
    |       |-- java
    |       |   `-- hello
    |       |       `-- org
    |       |           `-- json
    |       `-- resources
    |           |-- data
    |           `-- templates
    `-- target
        |-- classes
        |   |-- data
        |   |-- hello
        |   |-- org
        |   |   `-- json
        |   `-- templates
        |-- generated-sources
        |   `-- annotations
        |-- gs-handling-form-submission-0.1.0
        |   |-- META-INF
        |   `-- WEB-INF
        |       |-- classes
        |       |   |-- data
        |       |   |-- hello
        |       |   |-- org
        |       |   |   `-- json
        |       |   `-- templates
        |       `-- lib
        |-- maven-archiver
        `-- maven-status
            `-- maven-compiler-plugin
                `-- compile
                    `-- default-compile

    33 directories

java 文件在 hello 目录中。

【问题讨论】:

  • 使用ClassPathResource - 例如new ClassPathResource("/data/resorts.xml"),然后使用InputStreams。
  • 我努力换了语句 Document doc = builder.parse("src/main/resources/data/resorts.xml");使用语句 Resource resource = new ClassPathResource("/data/resorts.xml");文档 doc = builder.parse(IOUtils.toString(new ClassPathResource("package/resource").getInputStream()));仍然得到错误 java.io.FileNotFoundException: class path resource [package/resource] cannot be opens because it does not exist
  • 你能帮忙吗?我应该如何在 java 中解析该文件?
  • 你能添加完整的堆栈跟踪吗?处理资源时不应抛出 FileNotFoundException

标签: java spring maven ubuntu-14.04 relative-path


【解决方案1】:

您可能遇到了从 URI 类接收到位于 jar 中的文件的路径问题。

Application.class.getClassLoader().getResource("path-to/filename.txt").getPath()

输出:/path-to-your/application.jar!/path-to/filename.txt

如果您尝试创建文件对象或流到该路径,它将失败并显示FileNotFoundException

如果可能,您应该更改类 Document 以接收文件的内容或InputStream。 然后你可以使用类加载器来获取文件的流而不是路径。

在你的情况下:

InputStream is = Application.class.getClassLoader()
            .getResourceAsStream("data/resorts.xml");

然后使用is 对象创建文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 2021-09-21
    • 1970-01-01
    • 2021-12-05
    • 2012-04-04
    相关资源
    最近更新 更多