How can my project access its "resources" directory both when run in Eclipse and from a Maven-packaged jar file?
I'm working with Maven project in Eclipse (with help of m2e plugin). When I pack my project into jar-file (mvn install), all fi开发者_JS百科les 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?
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!
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:
精彩评论