io

Get content of a file line by line

This is an example of how to get the content of a file, line by line. We will make use of the org.apache.commons.io.FileUtils class, that provides file manipulation utilities. Getting the content of a file, line by line implies that you should:

  • Create a new File by converting the pathname string of the file into an abstract pathname.
  • Use readLines(File file) API method of org.apache.commons.io.FileUtils class, that reads the contents of a file line by line to a List of Strings using the default encoding for the VM.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;

public class GetContentLineByLine {
	public static void main(String[] args) {
		try {
			
			// We take a reference to an actual file on disk
			File file = new File("test.txt");
			


// We create a list with all the lines


List<String> content = FileUtils.readLines(file);
			 


// We print the content of every line
			int i = 0;


for (String line : content) {


    System.out.println("Line " + ++i + ": " + line);


}

  } catch (IOException e) {


e.printStackTrace();

  }
    }
}

Output:

Line 1: J
Line 2: a
Line 3: c
Line 4: o
Line 5: d
Line 6: e
Line 7: g
Line 8: e
Line 9: e
Line 10: k
Line 11: s
Line 12: !
Line 13: !
Line 14: !

 
This was an example of how to get the content of a file, line by line.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button