w3resource

Java: Read first 3 lines from a file


17. Read First 3 Lines of File

Write a Java program to read the first 3 lines of 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){
                System.out.println(strLine);
            }
           reader.close();
        } 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:

Flowchart: Read first 3 lines from a file


For more Practice: Solve these Related Problems:

  • Write a Java program to read only the first three lines of a file and print them to the console.
  • Write a Java program to extract the first three lines of a file and store them in an array.
  • Write a Java program to display the first three lines of a file and then skip reading the rest of the content.
  • Write a Java program to read the first three lines from a file and write them to a new file.

Go to:


PREV : Append Text to File.
NEXT : Find Longest Word in File.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.