Reputation: 7494
Not sure this basic question has already been answered on SO.
From the reference and also answers found on SO, I understand that in Eclipse a "source folder" is a folder that JDT will search for source files, and compile them.
It has been mentioned also that each source folder may have a counterpart to store compiled classes. Maybe this is why the content of the usual "src" folder of a project is compiled into a "bin" folder (when using such src/bin project option in Eclipse).
Question: Where to store additional non-source files, e.g. an icon, a security policy, or a data file? I guess this is in a "regular" folder, but at which level in the project hierarchy (usually)? Is it possible to put it in a source folder or not (why would we do that)? What happens after compilation, or export to a .jar file, under which conditions are the files copied in the .jar? Is the relative path preserved?
Upvotes: 4
Views: 8700
Reputation: 11949
This is purely conventional. You can store them all in src
if you want.
However, if you want to stick to Maven or Gradle conventions, then you should have something like that:
src/main/java
: main source file, that will be compiled and then distributed (jar, etc)src/main/resources
: main resources, distributed.src/test/java
: test source file, aka Junit testsrc/test/resources
: test resources.Maven would compile all Java into target/classes
and copy all resources into target/classes
. For test, it would be target/test-classes
.
Beside, if you want to access a resource, that in the Jar where your classes are, you should not use new File("...")
or Paths.get(...)
but getResourcesAsStream or its counterpart getResource:
try (Scanner scanner = new Scanner(MyClass.class.getResourceAsStream("/myfile.txt"))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
This would probably throw a NPE if /myfile.txt
was not found.
Upvotes: 7