从maven项目中的相对路径读取文件

reading a file from a relative path in a maven project

我的 java 文件在

/src/main/java/Test.java

我想从

中读取 属性 file/XML 文件

/src/main/resources/plugin.properties and/or

/src/main/resources/templates/basic_java.xml

当我尝试从 Test.java 读取这些文件时(当然是在部署之后),它无法读取并给出错误

java.io.FileNotFoundException: /target/plugin.properties (No such file or directory) at java.io.FileInputStream.open0(Native Method)

虽然我可以在[=33下找到plugin.propertiesbasic_java.xml =] 文件夹,但它无法读取这些文件。

我尝试了多种解决方案,包括:

1. getClass().getResource("Test.java");
2. new File(".").getCanonicalPath() + "target//plugin.properties";
3. ((URLClassLoader) Thread.currentThread().getContextClassLoader()).getURLs()
4. ((URLClassLoader) Thread.currentThread().getContextClassLoader()).getResourceAsStream("Test.java")
5. Thread.currentThread().getContextClassLoader().getSystemResources("Test.java");
6. new FileInputStream("src\main\resources\plugin.properties");
7. new FileInputStream("resources\plugin.properties");
8. new FileInputStream("src\main\resources\plugin.properties");
9. new FileInputStream("\plugin.properties");
10. new FileInputStream("\classes\plugin.properties");

但运气不好。

你需要这样的东西:

    InputStream inputStream = getClass().getResourceAsStream("/plugin.properties");
    String content = IOUtils.toString(inputStream);

IOUtils 来自 apache commons

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

这将从类路径打开输入流。

你能分享更多信息吗? 来自您的错误日志

java.io.FileNotFoundException: /target/plugin.properties (No such file or directory) at java.io.FileInputStream.open0(Native Method)

您似乎正在查找此路径中的文件

/target/plugin.properties

(那当然不存在)。我认为你必须做这样的事情

String pluginPath =System.getProperty("user.dir") + "/src/main/resources/plugin.properties";

在这种情况下,您的程序将搜索

中的文件

pluginPath: /YOUR_USER_DIR/src/main/resources/plugin.properties

有关 "user.dir" 的更多信息 Java "user.dir" property - what exactly does it mean?