Can't access files from src/main/resources via

2019-06-15 13:58发布

问题:

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?

回答1:

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");


回答2:

If the file is in

src/main/resources/file.dat

You can get the URL to the file :

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