How to create a Java String from the content of a file

The content of a File can be accessed using FileUtils from

Call the following method:, "UTF-8");

Here an example accessing the String content. First, it create a File Object with the file name, then Calls FileUtils.readFileToString setting the encoding to utf-8. The content is returned as a String. If an error occures an IOException is thrown.

1- Create the following java file:

public class FileStringContent {
    public static void main(String[] argv){
        File file = new File( "V:/tmp/test.txt" );
        String lines = ""; 
        try {
            lines = FileUtils.readFileToString(file, "UTF-8");
        } catch (IOException e) {
            // TODO Auto-generated catch block
        System.out.println( "The content of the file is: " + lines );

The output will be:

The content of the file is: This is a test


Commons IO

java io

Share this article:

Recent Comments