How do I get a specific line from a text file?

advertisements

This question already has an answer here:

  • How to read a specific line using the specific line number from a file in Java? 15 answers

I don't know how to get a specific line of text from a file. Let's say the text file is:

(1) john
(2) mark
(3) Luke

How can I get the second line of the text file (mark)? I just need to read it, not to edit it.


int n = 2;
String lineN = Files.lines(Paths.get("yourFile.txt"))
                    .skip(n)
                    .findFirst()
                    .get();

For pre-Java 8, you could do for instance

int n = 2;
Scanner s = new Scanner(new File("test.txt"));
for (int i = 0; i < n-1; i++) // Discard n-1 lines
    s.nextLine();
String lineN = s.nextLine();