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 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 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.util.List;

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) {




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.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Ilias Tsagklis

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

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

Inline Feedbacks
View all comments
Back to top button