My project has the following structure:
/src/main/java/ /src/main/resources/ /src/test/java/ /src/test/resources/
I have a file in /src/test/resources/test.csv
and I want to load the file from a unit test in /src/test/java/MyTest.java
I have this code which didn't work. It complains "No such file or directory".
BufferedReader br = new BufferedReader (new FileReader(test.csv))
I also tried this
InputStream is = (InputStream) MyTest.class.getResourcesAsStream(test.csv))
This also doesn't work. It returns null
. I am using Maven to build my project.
Using Java getResourceAsStream() This is an example of using getResourceAsStream method to read a file from src/main/resources directory. First, we are using the getResourceAsStream method to create an instance of InputStream. Next, we create an instance of InputStreamReader for the input stream.
This works when running inside and outside of a Jar file. PathMatchingResourcePatternResolver r = new PathMatchingResourcePatternResolver(); Resource[] resources = r. getResources("/myfolder/*"); Then you can access the data using getInputStream and the filename from getFilename .
Try the next:
ClassLoader classloader = Thread.currentThread().getContextClassLoader(); InputStream is = classloader.getResourceAsStream("test.csv");
If the above doesn't work, various projects have been added the following class: ClassLoaderUtil
1 (code here).2
Here are some examples of how that class is used:
src\main\java\com\company\test\YourCallingClass.java src\main\java\com\opensymphony\xwork2\util\ClassLoaderUtil.java src\main\resources\test.csv
// java.net.URL URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class); Path path = Paths.get(url.toURI()); List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// java.io.InputStream InputStream inputStream = ClassLoaderUtil.getResourceAsStream("test.csv", YourCallingClass.class); InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(streamReader); for (String line; (line = reader.readLine()) != null;) { // Process line }
Notes
Try:
InputStream is = MyTest.class.getResourceAsStream("/test.csv");
IIRC getResourceAsStream()
by default is relative to the class's package.
As @Terran noted, don't forget to add the /
at the starting of the filename
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