Digital Sanctum

Personal blog of Shane Witbeck Tags · Archive · About

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:


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

If the file is local but not on your classpath:


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.

Tags: #java#guava#how-to#read-file