Java read file line by line

Filed Under: Java

Today we will look into different java read file line by line methods. Sometimes we have to read file line by line to a String, for example calling a method by passing each line as String to process it.

Java Read File line by line

java read file line by line

We can read file line by line using different ways. Let’s look at some of them.

Java Read File line by line using BufferedReader

We can use java.io.BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached. Below is a simple program showing example for java read file line by line using BufferedReader.


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(
					"/Users/pankaj/Downloads/myfile.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();
		}
	}
}

Java Read File line by line using Scanner

We can use Scanner class to open a file and then read its content line by line. Below is the scanner example to read file line by line and print it.


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("/Users/pankaj/Downloads/myfile.txt"));
			while (scanner.hasNextLine()) {
				System.out.println(scanner.nextLine());
			}
			scanner.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

}

Java Read File line by line using Files

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


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("/Users/pankaj/Downloads/myfile.txt"));
			for (String line : allLines) {
				System.out.println(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Java Read File line by line using RandomAccessFile

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


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("/Users/pankaj/Downloads/myfile.txt", "r");
			String str;
			while ((str = file.readLine()) != null) {
				System.out.println(str);
			}
			file.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

That’s all for java read file line by line using different methods.

References:

Comments

  1. Sp says:

    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

  2. Bill Melendez says:

    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.

    1. Chirag HIrpara says:

      Here, rd is BufferReader reference.
      Try this.

      String a = rd.readLine();
      int i=0;

      while(i<1000 && a != null) {
      System.out.println(i+1+". "+a);
      a= rd.readLine();
      i++;
      }

  3. Dinesh says:

    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.

  4. Rinku says:

    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

  5. Vulco Viljoen says:

    Looks very good.

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

    1. HIMANSU NAYAK says:

      you need to seek the position and move the file pointer to it using RandomAccessFile

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages