How to read a specific line from a text file in Java

In this Java tutorial, I will show you the easiest way to read a specific line from a text file in Java. There is not only a single number of way to do this. There are a lot of ways to achieve your goal. But here in this tutorial, we will use the simplest way.

First of all, the text file can be small or large. Depending on the file size we should use the method so that our code works faster and efficiently.

Make A Multiplication Table Using Java Program

Java Program to read a specific line from a text file in Java

The below code can be used, later we will discuss several other methods. Choose the easiest method for you.



import java.io.*;
public class Readline {
             public static void main(String[] args) {
    String text = "";
    int lineNumber;
    try {
      FileReader readfile = new FileReader("myfile.txt");
      BufferedReader readbuffer = new BufferedReader(readfile);
      for (lineNumber = 1; lineNumber < 10; lineNumber++) {
        if (lineNumber == 7) {
          text = readbuffer.readLine();
        } else
          readbuffer.readLine();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    System.out.println(" The specific Line is: " + text);
  }
}

Read a specific line from a text file Java ( For small files)

The easiest way for small files is:

String specific_line_text = Files.readAllLines(Paths.get("myfile.txt")).get(n)

You just need to put the line number instead of in the get() method’s parameter.

Remove Duplicate Elements From Unsorted Array And Print Sorted

For example, if you want to get the particular line from a text file and the line number which you want to get is 11. Then you can use the below code

String specific_line_text = Files.readAllLines(Paths.get("file.txt")).get(11);

Read a particular line from a text file Java ( For large files)

try (Stream<String> all_lines = Files.lines(Paths.get("myfile.txt"))) {
specific_line_n = all_lines.skip(n-1).findFirst().get();
}

Assume that you need to find the text of line number 15.
Then you can use

try (Stream<String> all_lines = Files.lines(Paths.get("myfile.txt"))) {
specific_line_15 = all_lines.skip(14).findFirst().get();
}

Java Program To Check A Number is Palindrome or Not

Leave a Reply

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