Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maven exec:java : how to open and read a file in the resources directory?

Tags:

java

maven

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?

like image 322
wei Avatar asked May 16 '11 22:05

wei


3 Answers

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.

like image 80
wei Avatar answered Oct 16 '22 11:10

wei


Figure I'd add to the answers.

You can also use:

InputStream file = ClassLoader.getSystemResourceAsStream("res.txt");
like image 26
Cuga Avatar answered Oct 16 '22 10:10

Cuga


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.

like image 12
Jérôme Verstrynge Avatar answered Oct 16 '22 09:10

Jérôme Verstrynge