3

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.

Razib
  • 10,965
  • 11
  • 53
  • 80
Matthew
  • 157
  • 1
  • 9
  • this was already answered a couple of times: [here](http://stackoverflow.com/questions/2312756/in-java-how-to-read-from-a-file-a-specific-line-given-the-line-number) and [here](http://stackoverflow.com/questions/2138390/read-a-specific-line-from-a-text-file) – Tim Rijavec Apr 14 '15 at 21:06
  • @Stk, are you trying to get the line containing "mark" or just the second line? – aioobe Apr 14 '15 at 21:12
  • im trying to get a line number like the second line containing mark. im not looking for the person, just wanting to print out what is written on a specific line number. so if i want to see whats on line 2, i would input 2 and it will print out mark – Matthew Apr 14 '15 at 21:19

3 Answers3

2
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();
aioobe
  • 413,195
  • 112
  • 811
  • 826
2

There's no way to read a specific line without reading previous lines first. You could loop x number of times until you reach the line you desire.

For example:

FileReader fr = new FileReader("myfile.txt");
BufferedReader br = new BufferedReader(fr);
int lineNum = 2; //line of file to read
for(int i = 1; i < lineNum; i++)
     br.readLine();
System.out.println(br.readLine());
Thognar
  • 31
  • 1
0

You can use the Apache FileUtils class

File file = new File("file_name.txt");
String encoding = null; // default to platform
List<String> lines = FileUtils.readLines(file, encoding);
String line2 = lines.get(1);
MaxZoom
  • 7,619
  • 5
  • 28
  • 44
  • It seems that `findInLine` scans only current line, so it will fail if `mark` is not in first line. – Pshemo Apr 14 '15 at 21:16