I want to read a file that I have inside the test folder
../resources/files/ElTimoDeLaEstampeta.json
So I create this function that works when the file is on the folder
../resources/ElTimoDeLaEstampeta.json
protected String getResourceFileAsString (String resourceFileName) throws Exception {
Resource resource = new ClassPathResource(resourceFileName);
return new String(IOUtils.toByteArray(resource.getInputStream()));
}
But when is inside the files folder I got an exception, I've tried with with the same result
getResourceFileAsString ("files/ElTimoDeLaEstampeta.json")
getResourceFileAsString ("/files/ElTimoDeLaEstampeta.json")
getResourceFileAsString ("files.ElTimoDeLaEstampeta.json");
To read a file from resources folder you have to use the class loader.
Try the following code:
@Test
public void readFile() throws Exception {
InputStream inputStream = MaestroTest.class.getClassLoader().getResourceAsStream("folder/file.json");
String data = IOUtils.toString(inputStream, "UTF-8");
System.out.println(data);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.