19

here is the structure of my project.

proj
  ---src
    ----main
        ----java
            ----Main.java
        ----resources
             ----res.txt

I am using m2eclipse plugin with Eclipse. In Main.java, I have

File f = new File("res.txt");  System.out.println(f.getAbsolutePath());

When I run mvn exec:java, the path got printed out is "...\proj\res.txt". How can I make it look for the resource file in "...\proj\target\classes" directory?

EDIT:

Thanks for the answers to my original question. I have a follow-up questions:

So basically what I want to do is to have the Main class read the "res.txt" and then generate a new "newres.txt" to the resources directory so that I can package this new "newres.txt" to the jar file in the package phase later. Currently I mounted this exec:java to the prepare-package phase. How should I create this "newres.txt" in the resources directory without a hard-coded absolute path or depending on the directory structure of Maven?

wei
  • 6,629
  • 7
  • 40
  • 52

5 Answers5

20

I guess I will answer my own question, Thread.currentThread().getContextClassLoader().getResourceAsStream() works the best for me, especially when the project produces a jar dependency for another web project.

wei
  • 6,629
  • 7
  • 40
  • 52
16

Figure I'd add to the answers.

You can also use:

InputStream file = ClassLoader.getSystemResourceAsStream("res.txt");
Cuga
  • 17,668
  • 31
  • 111
  • 166
  • 1
    This solved my problem for me! Thank you so much for taking the time to write this solution up!!! – Wulf Aug 27 '13 at 21:27
12

Try

InputStream IS = Main.class.getResourceAsStream("res.txt");

to access the content of res.txt. Pay attention to the encoding of your text file (beware of defaults). If your maven project is set on UTF-8 for example, make sure res.txt is encoded in UTF-8 too, otherwise, you'll get funny errors at runtime.

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
  • More on this in a blog post I created recently: http://tshikatshikaaa.blogspot.nl/2012/07/maven-how-to-access-filesdata-in.html – Jérôme Verstrynge Jul 27 '12 at 13:26
  • See http://www.javaworld.com/javaqa/2003-08/01-qa-0808-property.html?page=2 about when to use a leading '/' for the resource path. – leo Jul 08 '13 at 14:29
1

Here is anther solution:

String str = "target/classes/res.txt";

InputStream is = new FileInputStream(new File(str));

If you exec java in root folder, and you resource will compile to target/classes folder, you can write you code like this.

Shuai Li
  • 2,426
  • 4
  • 24
  • 43
1

When run from eclipse, res.txt is created in/reader from the folder where eclipse is started. Hence the output.

If you want to make the code look at the file in a specific folder, which is present in your classpath, then you should try using getResourceAsStream() method.

Alternately you can specify the absolute path of the file.

Raghuram
  • 51,854
  • 11
  • 110
  • 122