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
InputStreamfor reading likegetClass().getResourceAsStream(<your-location>).moduleN/src/main/resources, and then it the data will be bundled into the jar file and independent of the filesystem path.Files.readString(…). Unless you really want to replace the platform independent line separators withSystem.lineSeparator()which is highly doubtful.PathandFilesto load from classpath. You just have to use the right filesystem rather than the default filesystem. But, of course, for a single resource, just usinggetResourceAsStreamis simpler.Path p = Path.of(MOCK_DATA_BASE_PATH, fileName);return Files.readString(p);