C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programs » Java file handling programs

Java program to read a file line by line

In this java program, we are going to learn how to read a file line by line and print the line on the output screen? Here, we are reading content of a file line by line and printing.
Submitted by IncludeHelp, on November 19, 2017

Given a file and we have to read its content line by line using java program.

For this program, I am using a file named "B.txt" which is located at "E:\" drive, hence the path of the file is "E:\B.txt", and the content of the file is:

    This is line 1
    This is line 2
    This is line 3
    This is line 4

Program to read file line by line in java

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class ReadLineByLine
{
	public static void main(String[] args)
	{
        // create object of scanner class.
		Scanner Sc=new Scanner(System.in);
		
		// enter file name.
		System.out.print("Enter the file name:");
		String sfilename=Sc.next();
		Scanner Sc1= null;
		FileInputStream fis=null;
		try
		{
		    FileInputStream FI=new FileInputStream(sfilename);
		    Sc1=new Scanner(FI);
		    
		    // this will read data till the end of data.
		    while(Sc1.hasNext())
		    {
		    	String data=Sc1.nextLine();
		    	
		    	// print the data.
		    	System.out.print("The file data is : " +data);
		    }
		}
		catch(IOException e)
		{
			System.out.println(e);
		}
	}

Output

Enter the file name: E:/B.txt
This is line 1
This is line 2
This is line 3
This is line 4








COMMENTS