Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a specific line from a text file in Java

Tags:

Is there any method to read a specific line from a text file ? In the API or Apache Commons. Something like :

String readLine(File file, int lineNumber) 

I agree it's trivial to implement, but it's not very efficient specially if the file is very big.

like image 599
Lluis Martinez Avatar asked Jan 26 '10 09:01

Lluis Martinez


People also ask

How do you read the second line of a text file in Java?

//read the file, line by line from txt File file = new File("train/traindata. txt"); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; line = br. readLine(); while(line != null) { lines = line.

How do you read a paragraph line by line in Java?

Using BufferedReader Class It belongs to java.io package. Java BufferedReader class provides readLine() method to read a file line by line. The signature of the method is: public String readLine() throws IOException.


1 Answers

String line = FileUtils.readLines(file).get(lineNumber); 

would do, but it still has the efficiency problem.

Alternatively, you can use:

 LineIterator it = IOUtils.lineIterator(        new BufferedReader(new FileReader("file.txt")));  for (int lineNumber = 0; it.hasNext(); lineNumber++) {     String line = (String) it.next();     if (lineNumber == expectedLineNumber) {         return line;     }  } 

This will be slightly more efficient due to the buffer.

Take a look at Scanner.skip(..) and attempt skipping whole lines (with regex). I can't tell if it will be more efficient - benchmark it.

P.S. with efficiency I mean memory efficiency

like image 193
Bozho Avatar answered Oct 16 '22 20:10

Bozho