Read File Line By Line In Java

In this tutorial we will learn how to read file in java . We can read content of file line by line in java using various ways as following .

  1. Read File Using BufferedReader
  2. Read File Using BufferedInputStream
  3. Using Scanner
  4. Java 8 Streams

Java Program to Read File Using BufferedReader

In this example we will read file using BufferedReader . Firstly we will create FileReader object and with the help of FileReader , we will create BufferedReader instance . Now we read text file line by line using readLine() method of BufferedReader.

package com.demo.file;

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

class BufferedReaderExample {

	public static void main(String[] args) {
		try {
			// Creates a FileReader
		   FileReader file = new FileReader("C://java_examples//newFile.txt");

			// Creates a BufferedReader
			BufferedReader reader = new BufferedReader(file);
			
			// Reads characters
			String line = reader.readLine();
			while (line != null) {
				System.out.println(line);
				// read next line
				line = reader.readLine();
			}
			reader.close();
			file.close();
		} catch (Exception e) {
			//print the exception 
			e.getStackTrace();
		}
	}
}

Output :

This is first line
This is Second line
This is Third line
This is Fourth line
This is Fifth line
This is Sixth line

Java Program to Read File Using BufferedInputStream

Now we will read text file using BufferedInputStream class . We create FileInputStream instance , then use it to create object BufferedInputStream . We read content of file using read() method of BufferedInputStream  class .

package com.demo.file;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

public class BufferedInputStreamExample {

	public static void main(String[] args) {

      try {
	   // Creates a FileInputStream
	FileInputStream file = new FileInputStream("C://java_examples//newFile.txt");

			// Creates a BufferedInputStream
			BufferedInputStream input = new BufferedInputStream(file);

			// Reads first byte from file
			int i = input.read();

			while (i != -1) {
				System.out.print((char) i);

				// Reads next byte from the file
				i = input.read();
			}
			// close BufferedInputStream
			input.close();
		} catch (Exception e) {
			// print exception
			e.getStackTrace();
		}

	}

}

Output :

This is first line
This is Second line
This is Third line
This is Fourth line
This is Fifth line
This is Sixth line

Java Program to Read File Using Scanner

We can use Scanner to read text file line by line . We create File object first , then use this file object to create instance of Scanner . We use Scanner hasNextLine() and nextLine() method to read file hasNextLine() – This method returns true if and only if there is next line in file .                          nextLine() – returns the entire line from the file.

package com.demo.file;

import java.io.File;
import java.util.Scanner;
public class ReadFileUsingScanner {
	
	public static void main(String[] args) {
		try {
		      // create a new file object
		      File file = new File("C://java_examples//newFile.txt");

		      // create an object of Scanner
		      // associated with the file
		      Scanner sc = new Scanner(file);
		      System.out.println("Reading File Using Scanner:");
		      while(sc.hasNextLine()) {
		        System.out.println(sc.nextLine());
		      }
		      // close scanner
		      sc.close();
		    } catch (Exception e) {
		    	//print exception
		      e.getStackTrace();
		    }
	}

}

Output :

Reading File Using Scanner:
This is first line
This is Second line
This is Third line
This is Fourth line
This is Fifth line
This is Sixth line

Read file line by line Using java 8

In this example we will read text file using java8 stream. We read file line by line using lines() method  of java.nio.file.Files .

package com.demo.file;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ReadFileUsingFiles {

    public static void main(String args[]) {

        String fileName = "C://java_examples//newFile.txt";

        //read file into stream, try-with-resources
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
		  
            stream.forEach(System.out::println);
        } catch (IOException e) {
		    //print Exception 
            e.printStackTrace();
        }
    }
}

Output:

This is first line
This is Second line
This is Third line
This is Fourth line
This is Fifth line
This is Sixth line

 

Reference :

BufferedReader API Doc
Files API Doc

Leave a Reply

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

52 − = 45