Read File From Classpath

March 20, 2018

I have a test that requires complex XML input. I decided to put this in a file in a resources directory, and then read it from there for the test.

My file is in src/test/resources/examples/RouteDataExample.xml

In order to retrieve this into the test code, I needed to do:

InputStream is = MyClassTest.class.getResourceAsStream("/examples/RouteDataExample.xml");
assertNotNull("Can't find example xml file", is);
final String TEST_XML = new BufferedReader(new InputStreamReader(is)).lines().collect(Collectors.joining("\n"));

The final line of code here will convert windows style line endings to unix ones.