tokhi
tokhi

Reputation: 21618

Can't access files from src/main/resources via a test-case

I have a file.dat in src/main/resources.

When I try to test a class which loads this file via a jar file, the test fails because its not able to find the file in the path (I/O Exception). The path which I get via test is:

/home/usr/workspace/project/target/test-classes/file.dat

but the file is not exist in target/test-classes any idea?

Upvotes: 20

Views: 28231

Answers (2)

Jonas Berlin
Jonas Berlin

Reputation: 3482

Files from src/main/resources will be available on the classpath during runtime of the main program, while files both from src/main/resources and src/test/resources will be available on the classpath during test runs.

One way to retrieve files residing on the classpath is:

Object content = Thread.currentThread().getContextClassLoader().getResource("file.dat").getContent();

.. where the type of content depends on the file contents. You can also get the file as an InputStream:

InputStream contentStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.dat");

Upvotes: 25

Georgi Eftimov
Georgi Eftimov

Reputation: 124

If the file is in

src/main/resources/file.dat

You can get the URL to the file :

getClass().getResource("/file.dat");

Upvotes: 5

Related Questions