Write a java program to Read a file line by line


This Java program demonstrates how to read a file line by line using the Scanner class and FileInputStream class. The program first prompts the user to enter the name of the file to be read. Then, it creates a Scanner object to read input from the console and reads the filename entered by the user.

The program then creates a FileInputStream object with the specified filename and passes it to a new Scanner object. The Scanner object is used to read the contents of the file line by line, using the nextLine() method.

The while loop iterates over each line in the file and prints it to the console using the println() method. The loop continues until there are no more lines to be read from the file, which is determined by the hasNext() method. If an IOException occurs during the file reading process, the program catches the exception and prints the error message.

Overall, this program demonstrates how to read a file line by line in Java using the Scanner and FileInputStream classes.

Source Code

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
 
public class ReadLine_ByLine
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the File Name :");
		String sfilename = input.next();
		Scanner sc = null;
		FileInputStream fis = null;
		try
		{
			FileInputStream FI = new FileInputStream(sfilename);
			sc = new Scanner(FI);
 
			// this will read data till the end of data.
			while (sc.hasNext())
			{
				String data = sc.nextLine();
				System.out.println(data);
			}
		}
		catch (IOException e)
		{
			System.out.println(e);
		}
	}
}

Output

Enter the File Name :file.txt
Python Exercises