How do I read file contents to string using commons-io?
Category: commons.io, viewed: 49361 time(s).
An example to read file contents and return the result as a string. This example using apache commons-io library version 1.3.1.
package org.kodejava.sample.commons.io;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class ReadFileToStringSample
{
public static void main(String[] args)
{
// In this example we use FileUtils class from Apache
// Commons IO (commons.io) to read the content of a
// file. FileUtils have two static methods called
// readFileToString(File file) and readFileToString(
// File file, String encoding) that we can user.
// Here we create an instance of File to hold our
// sample.txt file.
File file = new File("sample.txt");
try
{
// Read the entire contents of sample.txt
String content = FileUtils.readFileToString(file);
// For shake of this example we show the file content here.
System.out.println("File content: " + content);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Can't find what you are looking for? Join our
FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!