2

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.

Mel
  • 5,837
  • 10
  • 37
  • 42
sonal
  • 101
  • 1
  • 4
  • 13

2 Answers2

4

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.

Essex Boy
  • 7,565
  • 2
  • 21
  • 24
  • Thank you so much...it worked... even with the sub - folders inside target/classes/template/java.... – sonal Sep 21 '17 at 12:36
1

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?

Davide Patti
  • 3,391
  • 2
  • 18
  • 20