java

How to read the first line of a file in Java

In this tutorial, we are going to see different ways to read the first line of a file in Java.

  • By using BufferedReader.readLine() method
  • By using java.nio.file.Files.readAllLines() method

 

Java Program to read the first line of a file by using BufferedReader.readLine():

You can use BufferedReader.readLine() to get the first line. Note that the next call to readLine() will get you the 2nd line, and the next call will get the 3rd line, etc.

import java.io.*;

public class Main {
   public static void main(String[] args) throws IOException {
      //open the file
      FileReader file = new FileReader("file.txt");
      BufferedReader buffer = new BufferedReader(file);
      //read the 1st line
      String line = buffer.readLine();
      //display the 1st line
      System.out.println(line);
   }
}
 

Java Program to read the first line of a file by using java.nio.file.Files.readAllLines():

If the file is too large, use the following code. The java.nio.file.Files.readAllLines() method reads all lines of a file, the 0 indicates the first line of the file.

import java.nio.file.*;
import java.io.*;

public class Main {
   public static void main(String[] args) throws IOException {
      String line = Files.readAllLines(Paths.get("file.txt")).get(0);
      System.out.println(line);
   }
}
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *