Reading files from the classpath is a fairly common use case. Configuration files, HTML templates, CSV files and many more are all common use cases. This has always been a bit convoluted. The Java8 Paths and Files APIs made this a little simpler. Guava also has a few helper classes that make this very easy to accomplish.

Read Resource as String

Simple helper to load any resource on the classpath and convert it to a String. Here we are lazy and re-throw IOException's as unchecked exceptions.

public static String asString(String resource) {
    URL url = com.google.common.io.Resources.getResource(resource);
    try {
        return com.google.common.io.Resources.toString(url, Charsets.UTF_8);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

Here it is in action using a JUnit test.

@Test
public void testAsString() {
    String expected = "hello\nworld\n";
    String actual = Resources.asString("resources-test/hello.txt");
    assertEquals(expected, actual);
}

Read Resource as BufferedReader

Simple helper to load any resource on the classpath and convert it to a BufferedReader. BufferedReader's are much better for large files. Ideally you won't have very large files included in your JAR and they will be loaded externally so this might not be extremely useful.

public static BufferedReader asBufferedReader(String resource) {
    URL url = com.google.common.io.Resources.getResource(resource);
    try {
        CharSource charSource = com.google.common.io.Resources.asCharSource(url, Charsets.UTF_8);
        return charSource.openBufferedStream();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

Here it is in action using a JUnit test.

@Test
public void testAsBufferedReader() throws IOException {
    String expected = "hello\nworld\n";
    BufferedReader reader = Resources.asBufferedReader("resources-test/hello.txt");
    String actual = CharStreams.toString(reader);
    assertEquals(expected, actual);
}