Java: Read contents of resource file to String
If you have a resource text file – even if packaged in a JAR file – you can use the following Java 8(+) code to read the contents into a String. This code will also work in a static method (hence the ClassLoader.getSystemClassLoader()). If you’re in a normal method you can use the current instance’s classloader instead.
String contents = "";
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(filename);
if (inputStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
contents = reader.lines().collect(Collectors.joining(System.lineSeparator()));
}