从Java中的文本文件中读取特定行 [英] Reading a specific line from a text file in Java

查看:151
本文介绍了从Java中的文本文件中读取特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以从文本文件中读取特定行?在API或Apache Commons中。
类似于:

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.

推荐答案

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

可以,但仍然存在效率问题。

would do, but it still has the efficiency problem.

或者,您可以使用:

 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.

看看 Scanner.skip(..) 并尝试跳过整行(与正则表达式)。我不知道它是否会更有效率 - 基准它。

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。 效率我的意思是内存效率

P.S. with efficiency I mean memory efficiency

这篇关于从Java中的文本文件中读取特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆