0

I'm working with Maven project in Eclipse (with help of m2e plugin). When I pack my project into jar-file (mvn install), all files from "resources" are located in the root of jar.

Therefore, in my program I should use only bare file names:

File file = new File("foo.txt");

But when I build and run my project by Eclipse, I would have to use the relative path to the file:

File file = new File("src/main/resources/foo.txt");

What should I do to solve this problem?

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
Lampapos
  • 1,063
  • 1
  • 12
  • 26
  • You may find the answer in the following similar question's answer: http://stackoverflow.com/questions/4359876/how-to-load-reference-a-file-as-a-file-instance-from-the-classpath/4360001#4360001 – Jiri Patera Aug 17 '11 at 19:45

2 Answers2

1

To access your program's resources, don't use File, FileInputStream and similar classes. They will not work for anything inside a jar file.

Instead, use Foo.class.getResource(...) or .getResourceAsStream() to access your resources. (Read the documentation before doing so.)

I'm not sure if a program started from eclipse can access these - please try and report back!

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
  • Yes, a program started either from Eclipse or from a JAR file can access these as long as they are placed on CLASSPATH, i.e. in the `src/main/resources` directory. – Jiri Patera Aug 17 '11 at 19:51
  • Yes, it's working in Eclipse. But one detail: m2e plugin exclude src/main/resources from classpath (this problem is described [there](http://stackoverflow.com/questions/2273009/maven-and-eclipse-problem-looking-for-resources)). So you should erase one line from .classpath file and everything will work. Thanks! – Lampapos Aug 18 '11 at 07:39
0

Your package configuration in Eclipse is wrong, cause it sees src/main/resources as a package instead of a source folder.

The configuration in Eclipse must look like this: enter image description here

khmarbaise
  • 92,914
  • 28
  • 189
  • 235