简体   繁体   中英

reading a file from a relative path in a maven project

I have my java file in

/src/main/java/Test.java

and I want to read a property file/XML file from

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

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

When I try to read these files from Test.java (after deployment of course), it is not able to do so and giving the error

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

Though I can find the plugin.properties and basic_java.xml under /target/classes folder, yet it cannot read these files.

I have tried multiple solutions including :

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");

but no luck.

You need something like this:

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

IOUtils is is from apache commons

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

This will open an input stream from the classpath.

Could you share more info? From your error log

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

It looks like you're looking the file in this path

/target/plugin.properties

(that of course, doesn't exist). I think you have to do something like this

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

In this case your program will search the file in

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

More info about "user.dir" Java "user.dir" property - what exactly does it mean?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM