Intellipaat Back

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

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.

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:

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

}

Related questions

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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...