How do I read file contents to string using Commons IO?

In this example we use FileUtils class from Apache Commons IO to read the content of a file. FileUtils have two static methods called readFileToString(File) and readFileToString(File, String) that we can use.

An example to read file contents and return the result as a string can be seen below.




public class ReadFileToStringSample {
    public static void main(String[] args) {
        // Here we create an instance of File for sample.txt file.
        File file = new File("sample.txt");

        try {
            // Read the entire contents of sample.txt
            String content = FileUtils.readFileToString(file);
            System.out.println("File content: " + content);
        } catch (IOException e) {

Maven Dependencies


Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply