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?
The simplest approach uses an instance of the java. io. File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file.
In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().
Right click on maven project --->Click on Build Path ----->Click on New Source Folder. New source folder window will open, give the name to your folder example - src/test/source. click on Finish.
The resources folder belongs to the maven project structure where we place the configuration and data files related to the application. The location of the folder is “ src/main/resources “.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With