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

The content of a File can be accessed using FileUtils from org.apache.commons.io.

Call the following method:

org.apache.commons.io.FileUtils.readFileToString(fileName, "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:

import java.io.File;
import java.io.IOException;
 
import org.apache.commons.io.FileUtils;
 
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
            e.printStackTrace();
        }
         
        System.out.println( "The content of the file is: " + lines );
    }
     
}

The output will be:

The content of the file is: This is a test

References:

Commons IO

java io

Recent Comments