How can my project access its “resources” directory both when run in Eclipse and from a Maven-packaged jar file?

為{幸葍}努か 提交于 2019-12-25 03:54:23

问题


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?


回答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!




回答2:


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:



来源:https://stackoverflow.com/questions/7095539/how-can-my-project-access-its-resources-directory-both-when-run-in-eclipse-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!