从 Java 文本文件中读取特定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2138390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:01:38  来源:igfitidea点击:

Reading a specific line from a text file in Java

javaapache-commons-io

提问by Lluis Martinez

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

有什么方法可以从文本文件中读取特定行吗?在 API 或 Apache Commons 中。就像是 :

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.

我同意实现起来很简单,但是如果文件非常大,则效率不是很高。

采纳答案by Bozho

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.

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

P.S. with efficiencyI mean memory efficiency

PS有效率我的意思是内存效率

回答by pavium

If the lines you were reading were allthe same length, then a calculation might be useful.

如果您正在阅读的行的长度相同,那么计算可能会很有用。

But in the situation when the lines are different lengths, I don't think there's an alternative to reading them one at a time until the line count is correct.

但是在行长度不同的情况下,我认为在行数正确之前没有其他方法可以一次读取它们。

回答by Mykola Golubyev

If you are going to work with the same file in the same way (looking for a text at certain line) you can index your file. Line number -> offset.

如果您打算以相同的方式处理同一个文件(在特定行查找文本),您可以索引您的文件。行号 -> 偏移量。

回答by Andrzej Doyle

Not that I'm aware of.

不是我所知道的。

Be aware that there's no particular indexing on files as to where the line starts, so any utility method would be exactly as efficient as:

请注意,文件上没有关于行开始位置的特定索引,因此任何实用程序方法都与以下一样有效:

BufferedReader r = new BufferedReader(new FileReader(file));
for (int i = 0; i < lineNumber - 1; i++)
{
   r.readLine();
}
return r.readLine();

(with appropriate error-handling and resource-closing logic, of course).

(当然,具有适当的错误处理和资源关闭逻辑)。

回答by Dave Webb

Unfortunately, unless you can guarantee that every line in the file is the exact same length, you're going to have to read through the whole file, or at least up to the line you're after.

不幸的是,除非您能保证文件中的每一行都具有完全相同的长度,否则您将不得不通读整个文件,或者至少直到您要查找的行为止。

The only way you can count the lines is to look for the new line characters in the file, and this means you're going to have to read each byte.

计算行数的唯一方法是在文件中查找换行符,这意味着您将不得不读取每个字节。

It will be possible to optimise your code to make it neat and readable, but underneath you'll always be reading the whole file.

可以优化您的代码以使其整洁易读,但在底层您将始终阅读整个文件。

If you're going to reading the same file over and over again you could parse the file and create an index storing the offsets of certain line numbers, for example the byte count of where lines 100, 200 and so on are.

如果您要一遍又一遍地读取同一个文件,您可以解析该文件并创建一个索引来存储某些行号的偏移量,例如第 100、200 行等所在位置的字节数。

回答by Andreas Dolk

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.

因为文件是字节而不是面向行 - 任何通用解决方案的复杂性最多为 O(n),n 是文件大小(以字节为单位)。您必须扫描整个文件并计算行分隔符,直到您知道要读取文件的哪一部分。

回答by finnw

guavahas something similar:

番石榴有类似的东西:

List<String> Files.readLines(File file, Charset charset);

So you can do

所以你可以做

String line = Files.readLines(file, Charsets.UTF_8).get(lineNumber);

回答by Milson

Using File Utils:

使用文件实用程序:

File fileFeatures = new File(
                "Homework1AdditionalFiles/jEdit4.3/jEdit4.3ListOfFeatureIDs.txt");
String line = (String) FileUtils.readLines(fileFeatures).get(lineNumber);

回答by Jo?o Matos

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

根据这个答案,Java 8 使我们能够从文件中提取特定的行。该答案中提供了示例。