Whenever I run this code locally, the relative path for the file is working just fine but the Kubernetes pod deployment in pre-prod throws NoSuchFileException.
MOCK_DATA_BASE_PATH = "/data/mocks"
private static String getMockDataString(String fileName) {
try {
String filePath = MOCK_DATA_BASE_PATH + fileName;
return Files.lines(Paths.get(filePath))
.collect(Collectors.joining(System.lineSeparator()));
} catch (IOException e) {
logger.error("Unable to read file {} with reason {}", fileName, e.getMessage());
}
return null;
}
When I checked what my local returns for Path projectRoot = Paths.get("").toAbsolutePath();
it returned a local machine specific absolute path like so:/Users/username/path/to/project/mavenModule
while the Kubernetes deployment is plainly showing /
. Given such difference in both, I'm wondering how I can read the file in both platforms without exception.
The project directory is as such: Project has 3 mvn module1/module2/module2 directories. The files are in path/to/Project/data/mocks/
Real code examples of alternatives would be highly appreciated
Based on the comments I managed to make this approach work:
private static String getMockDataString(String fileName) throws MyServiceException {
String filePath = MOCK_DATA_BASE_PATH + fileName;
try (InputStream inputStream = MockResponseUtils.class
.getClassLoader().getResourceAsStream(filePath)) {
if (inputStream != null) {
return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8));
}
} catch (IOException e) {
throw new MyServiceException("Unable to load mock data for file " + MOCK_FILENAME);
}
return null;
}