Tutorial

How To Read a File Line-By-Line in Java

Updated on November 29, 2022
Default avatar

By Pankaj

How To Read a File Line-By-Line in Java

Introduction

In this article, you will learn about different ways to use Java to read the contents of a file line-by-line. This article uses methods from the following Java classes: java.io.BufferedReader, java.util.Scanner, Files.readAllLines(), and java.io.RandomAccessFile.

Reading a File Line-by-Line using BufferedReader

You can use the readLine() method from java.io.BufferedReader to read a file line-by-line to String. This method returns null when the end of the file is reached.

Here is an example program to read a file line-by-line with BufferedReader:

ReadFileLineByLineUsingBufferedReader.java
package com.journaldev.readfileslinebyline;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileLineByLineUsingBufferedReader {

	public static void main(String[] args) {
		BufferedReader reader;

		try {
			reader = new BufferedReader(new FileReader("sample.txt"));
			String line = reader.readLine();

			while (line != null) {
				System.out.println(line);
				// read next line
				line = reader.readLine();
			}

			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Continue your learning with the BufferedReader API Doc (Java SE 8).

Reading a File Line-by-Line using Scanner

You can use the Scanner class to open a file and then read its content line-by-line.

Here is an example program to read a file line-by-line with Scanner:

ReadFileLineByLineUsingScanner.java
package com.journaldev.readfileslinebyline;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFileLineByLineUsingScanner {

	public static void main(String[] args) {
		try {
			Scanner scanner = new Scanner(new File("sample.txt"));

			while (scanner.hasNextLine()) {
				System.out.println(scanner.nextLine());
			}

			scanner.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

}

Continue your learning with the Scanner API Doc (Java SE 8).

Reading a File Line-by-Line using Files

java.nio.file.Files is a utility class that contains various useful methods. The readAllLines() method can be used to read all the file lines into a list of strings.

Here is an example program to read a file line-by-line with Files:

ReadFileLineByLineUsingFiles.java
package com.journaldev.readfileslinebyline;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class ReadFileLineByLineUsingFiles {

	public static void main(String[] args) {
		try {
			List<String> allLines = Files.readAllLines(Paths.get("sample.txt"));

			for (String line : allLines) {
				System.out.println(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Continue your learning with the Files API Doc (Java SE 8).

Reading a File Line-by-Line using RandomAccessFile

You can use RandomAccessFile to open a file in read mode and then use its readLine method to read a file line-by-line.

Here is an example program to read a file line-by-line with RandomAccessFile:

ReadFileLineByLineUsingRandomAccessFile.java
package com.journaldev.readfileslinebyline;

import java.io.IOException;
import java.io.RandomAccessFile;

public class ReadFileLineByLineUsingRandomAccessFile {

	public static void main(String[] args) {
		try {
			RandomAccessFile file = new RandomAccessFile("sample.txt", "r");
			String str;

			while ((str = file.readLine()) != null) {
				System.out.println(str);
			}

			file.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Continue your learning with the RandomAccessFile API Doc (Java SE 8).

Conclusion

In this article, you learned about different ways to use Java to read the contents of a file line-by-line.

Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 9, 2020

SO what im trying to do is reading each line from a file (named fileName) and writing it into a new file (named fileName2), so basically a copier. How would you do that?

- Ana Pathak

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 29, 2020

    Is there a way to read a specific line from a file without first reading all previous lines if you know the line length? I’m seeking something analogous to the BASIC code OPEN FILE$ AS 1 LEN = 5 READ #1, 5, LINE% READ #1, LINE%, DESC$

    - Jeff Mullen

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      November 12, 2019

      I write a file handling program, I read data from file. In a file a create a table(name,age,clg) when I read data,I get data with column name but I want only data nat file name please suggest me how can do

      - Sp

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 9, 2019

        Thanks for your tutorials. Is there a way to grab each individual line and assign it to a variable? Somthing like String line [ i } = reader.readLine(); String line1 = line[ o ]; String line2 = line [1 ]; and so on. I tried this and I get the first line on the first line1 string with the rest as nulls. Then i get the first and second line with the rest as nulls on line2 string.

        - Bill Melendez

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 13, 2019

          I want to create a java program to read input from text file but don’t want to read all the lines at once,Instead I want my Java program to read Input as in when required line by line. need help… Thanks a lot , for giving a shot to my query.

          - Dinesh

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            December 17, 2014

            Hello I have to create java program in such a way that output should be print on thermal printer for which paper size ,font size etc should be modified with text file ( template )…I have created program which read normal file and print but how to handle paper size anf font size things pls help me out there

            - Rinku

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              February 6, 2013

              Looks very good. Would you be so kind to give an example on how to read random lines from a file?

              - Vulco Viljoen

                Try DigitalOcean for free

                Click below to sign up and get $200 of credit to try our products over 60 days!

                Sign up

                Join the Tech Talk
                Success! Thank you! Please check your email for further details.

                Please complete your information!

                Get our biweekly newsletter

                Sign up for Infrastructure as a Newsletter.

                Hollie's Hub for Good

                Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                Become a contributor

                Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                Welcome to the developer cloud

                DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                Learn more
                DigitalOcean Cloud Control Panel