Write a Java program to read first three lines from a file


This code reads the first three lines of a text file named "file.txt" using the LineNumberReader and BufferedReader classes from the java.io package. The main method creates an instance of LineNumberReader and initializes it with a FileInputStream object that reads the "file.txt" file. The InputStreamReader is used to read the contents of the file using the UTF-8 character set.

The while loop reads each line of the file using readLine() method of LineNumberReader until the end of the file is reached or the line number exceeds 3. The condition (line = reader.readLine()) != null checks if the line is not null, and reader.getLineNumber() <= 3 checks if the line number is less than or equal to 3. The contents of each line are printed on the console using System.out.println(line) .

The try-catch block is used to handle the FileNotFoundException and IOException that may occur while reading the file. If the file is not found or cannot be read, an appropriate error message is displayed on the console. Note that this code assumes that the "file.txt" file exists in the current directory and is readable.

Source Code

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.LineNumberReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
public class ReadFirst_ThreeLines
{
    public static void main(String a[])
	{
        BufferedReader br = null;
        String line = "";
        try
		{
			LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream("file.txt"), "UTF-8"));
			while(((line = reader.readLine()) != null) && reader.getLineNumber() <= 3)
			{
				System.out.println(line);
			}
           reader.close();
        }
		catch(FileNotFoundException e)
		{
            System.err.println("File Not Found");
        }
		catch(IOException e)
		{
            System.err.println("Unable to Read the File.");
        }
     }
}

Output

This is Java Programs