Apache FileUtils reading file



This example demonstrates how to read a text file into a string and into a list of strings using the Apache commons library.

Maven Dependency

Let's add maven dependency before creating these examples:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

Apache FileUtils reading file

Let's first create a text file named words.txt located in the src/main/resources directory. Add below content to this file:
blue, tank, robot, planet, wisdom, cherry, 
chair, pen, keyboard, tree, forest, plant
sky, movie, white, colour, music, dog, cat
The below example reads a text file into a string and into a list of strings.
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.FileUtils;

public class ReadFileEx {
    
    public static void main(String[] args) throws IOException {
        
        File myfile = new File("src/main/resources/words.txt");
        
        String contents = FileUtils.readFileToString(myfile, 
                StandardCharsets.UTF_8.name());
        
        System.out.println(contents);
        
        List lines = FileUtils.readLines(myfile, 
                StandardCharsets.UTF_8.name());
        
        System.out.printf("There are %d lines in the file\n", lines.size());
        
        System.err.printf("The second line is: %s", lines.get(1));
    }
}

Related Posts

Comments