Apache Commons IO with LineIterator to read file content

Tags: Apache Commons IO

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

There are two examples to show you how to use Apache Commons IO with LineIterator to read file content from InputStream or Reader object.

Example to use IOUtils.lineIterator() with InputStream

package simplesolution.dev;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;

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

public class IOUtilsLineIteratorWithInputStreamExample {

    public static void main(String... args) {
        String fileName = "D:\\data\\sample.txt";
        try(InputStream inputStream = new FileInputStream(fileName)){
            LineIterator lineIterator = IOUtils.lineIterator(inputStream, "UTF-8");
            while(lineIterator.hasNext()){
                String line = lineIterator.nextLine();
                System.out.println(line);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Example to use IOUtils.lineIterator() with Reader

package simplesolution.dev;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;

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

public class IOUtilsLineIteratorWithReaderExample {

    public static void main(String... args) {
        String fileName = "D:\\data\\sample.txt";
        try(Reader reader = new FileReader(fileName)){
            LineIterator lineIterator = IOUtils.lineIterator(reader);
            while(lineIterator.hasNext()){
                String line = lineIterator.nextLine();
                System.out.println(line);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Happy Coding 😊