Apache Commons IO to read text file content as a list of Strings

Tags: Apache Commons IO

Java Code Examples for org.apache.commons.io.IOUtils.readLines()

Example below using readLines() method to read file content from InputStream or Reader and return a list of Strings.

Example to use IOUtils.readLines() with InputStream

package simplesolution.dev;

import org.apache.commons.io.IOUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class IOUtilsReadLinesWithInputStreamExample {

    public static void main(String... args) {
        String fileName = "D:\\data\\sample.txt";
        try(InputStream inputStream = new FileInputStream(fileName)){
            List<String> fileContent = IOUtils.readLines(inputStream, "UTF-8");
            for(String line: fileContent) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Example to use IOUtils.readLines() with Reader

package simplesolution.dev;

import org.apache.commons.io.IOUtils;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class IOUtilsReadLinesWithReaderExample {

    public static void main(String... args) {
        String fileName = "D:\\data\\sample.txt";
        try(Reader reader = new FileReader(fileName)){
            List<String> fileContent = IOUtils.readLines(reader);
            for(String line: fileContent) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Happy Coding 😊