2

I have a Java application that I build with Maven. I have a resources folder com/pkg/resources/... that I need to access files from. For example directory.txt. I've been looking at various tutorials and other SO answers, but none seem to work for me. Right now I have:

ClassLoader classLoader = getClass.getClassLoader();
File file = new File(classLoader.getResource("/directory.txt");

When I output f.length I get a result of 0 bytes. I've also tried:

InputStream is = (this.getClass().getClassLoader().getResourceAsStream("/directory.txt"));
try{
    File file = File.createTempFile("dir", ".txt");
    Files.copy(is, file.toPath());
} catch (IOException e) {
    e.printStackTrace();
}

But that code does not work either. I haven't worked with accessing files from a JAR before. Any ideas on what might be going wrong?

SVN600
  • 345
  • 1
  • 5
  • 19

3 Answers3

0

First, use the "src/main/resources" folder, for example in resources you can have a file named: dummy.txt

Full path should be: src/main/resources/dummy.txt

In some class you could read dummy.txt as folow:

String dummy = new String(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("/dummy.txt")));

Also, if you want to have folders in there you can have it. For example:

src/main/resources/com/pkg/resources/dummy.txt

String dummy = new String(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("/com/pkg/resources/dummy.txt")));

Have as consideration that in this example we are not doing nothing with the classpath information in our pom.xml

Note: IOUtils is from commons-io , for example:

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId> 
            <version>2.4</version>
</dependency>
MikaelF
  • 3,518
  • 4
  • 20
  • 33
Daniel Hernández
  • 4,078
  • 6
  • 27
  • 38
0

If the maven not include the resource folder in your jar you can use the following code to include the resource folder in jar. Maven by default search the resources folder in src/main/java/resources and if your resource is not in that path , maven not include in the class path. Below are code to include explicitly the resource folder in classpath. Add in your pom.xml

<build>
    ....
    <resources>
        <resource>
            <directory>path-of-resource-folder</directory>
        </resource>
    </resources>
    ....
</build>
Ctorres
  • 468
  • 6
  • 19
Ashwani Tiwari
  • 1,497
  • 18
  • 28
-1

Resources go into src/main/resources/my/package/whatever. Once they are they, Maven will include them in the output jar and you can reference them from classpath. I typically use Guava. If foo.bar.baz.MyClass has a corresponding file foo/bar/baz/somefile.txt, I would write.

 URL url = Resources.getResource("somefile.txt", MyClass.class); 
 ByteSource source = Resources.asByteSource(url);
 try (InputStream is = source.openSource()) {
    // consume contents
 }
bmargulies
  • 97,814
  • 39
  • 186
  • 310