简体   繁体   中英

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?

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

If the file is in

src/main/resources/file.dat

You can get the URL to the file :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM