Reading a specific line from a text file in Java

后端 未结 9 661
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 07:34

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)


        
相关标签:
9条回答
  • 2020-11-27 08:15

    Because files are byte and not line orientated - any general solutions complexity will be O(n) at best with n being the files size in bytes. You have to scan the whole file and count the line delimiters until you know which part of the file you want to read.

    0 讨论(0)
  • 2020-11-27 08:15

    According to this answer, Java 8 enables us to extract specific lines from a file. Examples are provided in that answer.

    0 讨论(0)
  • 2020-11-27 08:17
    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

    0 讨论(0)
提交回复
热议问题