Monday, July 30, 2012

Exploring Google Guava

I am pretty impressed with the simplicity of Google Guava API. We have been using Apache Commons for many years, but Guava has good support for generics and hence is a better choice for new Java development.

For e.g. to read a text file as a list of strings, you need just 2 lines of code.

//read a file from the classpath, as we want to avoid absolute paths..
File file = new File(getClass().getResource("/com/company/project/test.txt").getFile());
//pass a proper charset to ensure proper encoding
List<String>lines = Files.readLines(file, Charsets.UTF_8); 
  

Another alternate method to read the entire content of the file as a string -
public static String toString(File file,Charset charset)


To read a binary file into a byte array, use the following utility method -
public static byte[] toByteArray(File file)

Similar simple methods exist for writing files too !..