Java Exercises: Read first 3 lines from a file

Java Input-Output: Exercise-17 with Solution

Write a Java program to read first 3 lines from a file.

Sample Solution:

Java 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 Exercise17 {
    public static void main(String a[]){
        BufferedReader br = null;
        String strLine = "";
        try {
            LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream("/home/students/test.txt"), "UTF-8"));
             while (((strLine = reader.readLine()) != null) && reader.getLineNumber() <= 3){
        } catch (FileNotFoundException e) {
            System.err.println("File not found");
        } catch (IOException e) {
            System.err.println("Unable to read the file.");

Sample Output:

Welcome to w3resource.com.                                                                                    
Append this text.Append this text.Append this text.                                                           
Append this text.


Flowchart: Read first 3 lines from a file

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to append text to an existing file.
Next: Write a Java program to find the longest word in a text file.

What is the difficulty level of this exercise?

Inviting useful, relevant, well-written and unique guest posts