0 points

Load resource content with vanila Java


dashboard

Fri Aug 14 2020 12:00:13 GMT+0000 (UTC)

Posted by @hosuaby #java

String resourcePath = "com/adelean/junit/jupiter/resource.txt";
ClassLoader classLoader = getClass().getClassLoader();
              
StringBuilder textBuilder = new StringBuilder();
              
try (InputStream resourceAsStream = classLoader.getResourceAsStream(resourcePath);
     InputStreamReader streamReader = new InputStreamReader(resourceAsStream);
     BufferedReader bufferedReader = new BufferedReader(streamReader)) {
    int c = 0;
    while ((c = bufferedReader.read()) != -1) {
        textBuilder.append((char) c);
    }
} catch (IOException ioException) {
    // handle exception
}
              
String resourceContent = textBuilder.toString();
content_copy Copy