Java Reading text files with Apache commons IOUtils

Apache Commons IO is a library of utilities to assist with developing IO functionality in Java. It contains an IOUtils class, which provides static utility methods for input & output operations.
We add this Maven dependency to the pom.xml file.
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

Java Reading text files with Apache commons IOUtils

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.io.IOUtils;

public class ReadTextFileExample {

    public static void main(String[] args) throws FileNotFoundException, 
            IOException {
        
        String fileName = "src/main/resources/sample.txt";

        try (FileInputStream inputStream = new FileInputStream(fileName)) {
            
            String allLines = IOUtils.toString(inputStream, "UTF-8");
            System.out.println(allLines);
        }
    }
}
The IOUtils.toString() method gets the contents of an InputStream as a String using the specified character encoding. This method may not be suitable for larger files, since it reads the whole contents into the memory.
In the second example, we read the file contents into a string.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class ReadTextFileExample {

    public static void main(String[] args) throws IOException {
        
        String fileName = "src/main/resources/sample.txt";
        
        String content = FileUtils.readFileToString(new File(fileName), "UTF-8");
        System.out.println(content);
    }
}
The FileUtils.readFileToString() method reads the contents of a file into a String. The file is always closed.




Comments