Reading a file from a jar or anywhere in the class path?

I am trying to create an application that creates a resource file in a bank, but I would like the project to be run in eclipse. I have a basic maven structure for my project, and I'm not sure how to read the file that it found and used when starting from the JAR or from eclipse. Thought?

Composition:

src/main/java
src/main/resources/file.txt

Current reading method:

getClass().getResourceAsStream("/file.txt")

Is there a read method that will display src / main / resources / *, as well as the root level of the JAR (where the resources are deployed)?

+5
source share
2 answers

. src/main/resources target/classes , , Maven Eclipse ( Eclipse ).

JAR, target/classes " ", .

, file.txt, , ( ):

// Retrieve resource
InputStream is = getClass().getResourceAsStream( "/file.txt" );

// Do something with the resource

...

, , .

: maven-eclipse, :

$ mvn archetype:generate -DgroupId=com.stackoverflow -DartifactId=q2467362 -Dversion=1.0-SNAPSHOT
...
$ cd q2467362
$ mkdir -p src/main/resources
$ mvn eclipse:eclipse
...
$ cat .classpath
<classpath>
  <classpathentry kind="src" path="src/test/java" output="target/test-classes" including="**/*.java"/>
  <classpathentry kind="src" path="src/main/java" including="**/*.java"/>
  <classpathentry kind="src" path="src/main/resources" excluding="**/*.java"/>
  <classpathentry kind="output" path="target/classes"/>
  <classpathentry kind="var" path="M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar" sourcepath="M2_REPO/junit/junit/3.8.1/junit-3.8.1-sources.jar"/>
  <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>

src/main/resources , . POM ( resources, )?

+8

All Articles