Read a file from resources folder with getResource() for static and non-static context:
File Location:
src/main/resources
|--->mock-response/monga-response.json
Method implementation for non-static context:
public String readResponseFromFile(String fileName) throws URISyntaxException, IOException {
File inputFile = new File(this.getClass().getResource("/" + fileName).toURI());
return FileUtils.readFileToString(inputFile);
}
If you want to load a file from the resources folder from a static context you must use the class name.
Method Implementation for static context:
public static String readResponseFromFile(String fileName) throws URISyntaxException, IOException {
File inputFile = new File(MockingUtil.class.getClassLoader().getResource(fileName).getFile());
return FileUtils.readFileToString(inputFile);
}
Method Call:
dataFetcher.setHttpClient(MockingUtil.getMockHttpClient(MockingUtil.readResponseFromFile("mock-response/monga-response.json")));
Resource Link:
https://memorynotfound.com/load-file-resources-folder-java/
File Location:
src/main/resources
|--->mock-response/monga-response.json
Method implementation for non-static context:
public String readResponseFromFile(String fileName) throws URISyntaxException, IOException {
File inputFile = new File(this.getClass().getResource("/" + fileName).toURI());
return FileUtils.readFileToString(inputFile);
}
If you want to load a file from the resources folder from a static context you must use the class name.
Method Implementation for static context:
public static String readResponseFromFile(String fileName) throws URISyntaxException, IOException {
File inputFile = new File(MockingUtil.class.getClassLoader().getResource(fileName).getFile());
return FileUtils.readFileToString(inputFile);
}
Method Call:
dataFetcher.setHttpClient(MockingUtil.getMockHttpClient(MockingUtil.readResponseFromFile("mock-response/monga-response.json")));
Resource Link:
https://memorynotfound.com/load-file-resources-folder-java/
No comments:
Post a Comment