How to Read File Contents in Java the Easy Way with Guava

Published: 30 Nov 2012

Here's an easy and no-frills way to read the contents of a text file using Guava:

If the file is on your classpath:

import com.google.common.base.Charsets;
import com.google.common.io.Files;

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

If the file is local but not on your classpath:

import com.google.common.base.Charsets;
import com.google.common.io.Files;

String content = Files.toString(new File("/home/user/foo.txt"), Charsets.UTF_8);

Not using Guava already? Look here for instructions on how to add it to your project.