Program to demonstrate how to read a file contents and convert it to String using Apache commons-io API in Java.
Output of the program :
package com.hubberspot.apache.commons.examples;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class FileContentsToString {
public static void main(String[] args) {
// Create a File object and pass name of the file along
// with its path whose contents is to be read
File file = new File("C:/Program Files/glassfish-3.1.2/glassfish/domains/" +
"domain1/logs/server.log");
try {
// org.apache.commons.io package has a class by name
// FileUtils which has a method called as readFileToString()
// This method takes in a file object and return back
// contents of file in the form of String representing
// file contents as a String object
String fileContents = FileUtils.readFileToString(file);
// In order to print the contents of file on the console
// we just print the it on the console using
// System.out.println(String)
System.out.println(fileContents);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of the program :
