Tuesday, August 6, 2013

How to Convert a File Content in a Java String? A Simple Example Using Guava API...

Recently in a project I got into this task of converting an entire file into string. After googling a bit, I got this "guava" API to help. There are other APIs available from Apache etc, but I found Guava easy to use and have been working quite nice so far.

Although writing your own would not be much difficult either, but then why to re-invent the wheel! :)

You can use this for few doing some other interesting stuff as well like Collection, cahcing etc. Details you can find at Guava's home page.

If you are using Maven you can update the dependencies in your project by using snippet given at
http://code.google.com/p/guava-libraries/wiki/UseGuavaInYourBuild

Else, you can download the JAR from its home page : http://code.google.com/p/guava-libraries/


So, once you have added the dependencies/jar you can play with it. Here is a demo code for converting  a file's content into a Java String:


package com.demo.fileops;

import java.io.File;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.nio.charset.Charset;

import com.google.common.io.Files;

public class FiletoStringGuavaStyle{
 
 String fileContent = null;

 /** A function to convert File Content into String **/
 public static String loadFileIntoString() throws IOException{ 
  
  String path = "C:"+ File.separator + "Users" +  File.separator  + "myTextFile.txt";  // location -> C:/Users/myTextFile.txt
  
  this.fileContent = Files.toString(new File(path), Charset.defaultCharset()); // use of Guava here
  
  System.out.println("fileContent=" + this.fileContent);
   
  return this.fileContent; 
 }
 
 public static void main(String args[]){
  
  String content = FiletoStringGuavaStyle.loadFileIntoString() ; 
 }

} 




No comments:

Post a Comment

Prototype

Prototype is another creation pattern. Intent:  - Intent is to create objects by cloning existing instance  - Specify the kinds of obj...