Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to read a file contents line by line using Apache commons-io API in Java ?

Program to demonstrate how to read a file contents line by line using commons-io API in Java.

package com.hubberspot.apache.commons.examples;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class ReadFileLineByLine {

    public static void main(String[] args) {
        
        // Create a File object and pass name of the file along 
        // with its path whose contents is to be read 
        File file = new File("C:/Program Files/glassfish-3.1.2/glassfish/domains/" +
          "domain1/logs/server.log");

        try {
            
            // org.apache.commons.io package has a class by name
            // FileUtils which has a method called as readLines()
            // This method takes in a file object and return back 
            // contents of file in the form of List representing 
            // each line as String object  
            List fileContents = FileUtils.readLines(file);
            
            // In order to print the contents of file on the console
            // we use for loop which iterates over List line by line
            // and prints on the console. 
            for (String line : fileContents) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}



Output of the program : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot