There are many possible ways of doing this:
Read the file completely (only suitable for smaller files)
public static String readFileFromResources(String filename) throws URISyntaxException, IOException {
URL resource = YourClass.class.getClassLoader().getResource(filename);
byte[] bytes = Files.readAllBytes(Paths.get(resource.toURI()));
return new String(bytes);
}
Read in the file line by line (also suitable for larger files)
private static String readFileFromResources(String fileName) throws IOException {
URL resource = YourClass.class.getClassLoader().getResource(fileName);
if (resource == null)
throw new IllegalArgumentException("file is not found!");
StringBuilder fileContent = new StringBuilder();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(new File(resource.getFile())));
String line;
while ((line = bufferedReader.readLine()) != null) {
fileContent.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return fileContent.toString();
}
The most comfortable way is to use apache-commons.io
private static String readFileFromResources(String fileName) throws IOException {
return IOUtils.resourceToString(fileName, StandardCharsets.UTF_8);
}