Java: Reading resource file into String

Suppose you have file in the following path of you application src/main/resources/file/user.txt
In order to load resource file we can use the following option:

    
URL url= Thread.currentThread().getContextClassLoader().getResource("user.txt");
File file = new File(url.getFile());

If you already have guava library in your classpath you can use the following way:

URL url = Resources.getResource("user.txt");
File file = new File(url.getFile());

Need to admit that getResource under the hood the uses the first option we gave. So no need to have extra dependency in your classpath just because this option.

Now lets see how we can read file into string:

Prior to java 7:

StringBuffer content = new StringBuffer();

BufferedReader br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().
       getResourceAsStream("user.txt"), "UTF-8"));
for (int c = br.read(); c != -1; c = br.read()) {
   content.append((char)c);
};




Using Guava:

URL url = Resources.getResource("user.txt");
String content = Resources.toString(url, Charsets.UTF_8);

Using java 7

URL url = Thread.currentThread().getContextClassLoader().getResource("user.txt");
Path path = Paths.get(url.toURI());
content = new String(Files.readAllBytes(path));

Using Apache IO

URL url = Thread.currentThread().getContextClassLoader().getResource("user.txt");
String content = IOUtils.toString(url, "UTF-8");