Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (10.2k points)

My project has the following structure:





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/

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.

1 Answer

0 votes
by (46k points)

Try this:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();

InputStream is = classloader.getResourceAsStream("test.csv");

If the over doesn't work, several projects have been attached to the following class: ClassLoaderUtil1 (code here).

Here are some instances of how that class is used:





URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class);

Path path = Paths.get(url.toURI());

List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);


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


Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories