java 用Java读取文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2714385/
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-10-29 22:29:42  来源:igfitidea点击:

Read text file in Java

javafile-iotext-files

提问by frank wang

I have a text file. I would like to retrieve the content from one line to another line. For example, the file may be 200K lines. I want to read the content from line 78 to line 2735. Since the file may be very large, I do not want to read the whole content into the memory.

我有一个文本文件。我想将内容从一行检索到另一行。例如,文件可能是 200K 行。我想读取第78行到第2735行的内容。由于文件可能很大,我不想将整个内容读入内存。

采纳答案by Bart Kiers

Here's a start of a possible solution:

这是一个可能的解决方案的开始:

public static List<String> linesFromTo(int from, int to, String fileName)
        throws FileNotFoundException, IllegalArgumentException {
    return linesFromTo(from, to, fileName, "UTF-8");
}

public static List<String> linesFromTo(int from, int to, String fileName, String charsetName)
        throws FileNotFoundException, IllegalArgumentException {

    if(from > to) {
        throw new IllegalArgumentException("'from' > 'to'");
    }
    if(from < 1 || to < 1) {
        throw new IllegalArgumentException("'from' or 'to' is negative");
    }

    List<String> lines = new ArrayList<String>();
    Scanner scan = new Scanner(new File(fileName), charsetName);
    int lineNumber = 0;

    while(scan.hasNextLine() && lineNumber < to) {
        lineNumber++;
        String line = scan.nextLine();
        if(lineNumber < from) continue;
        lines.add(line);
    }

    if(lineNumber != to) {
        throw new IllegalArgumentException(fileName+" does not have "+to+" lines");
    }

    return lines;
}

回答by Michael Borgwardt

Use BufferedReader.readLine()and count the lines. You'll keep only the buffer size and the current line in memory.

使用BufferedReader.readLine()并计算行数。您将只保留缓冲区大小和内存中的当前行。

And no, it's not possible to get to line 3412 without reading the whole file up to that point (unless your lines all have a fixed size).

不,不可能在没有读取整个文件的情况下到达第 3412 行(除非您的行都具有固定大小)。

回答by flopex

I would suggest using a RandomAccessFile, this class enables you to jump to a specific location in a file. So if you want to read the last line of the file you don't have to read all of the previous lines you can just jump to that line.

我建议使用 RandomAccessFile,这个类使您能够跳转到文件中的特定位置。因此,如果您想阅读文件的最后一行,则不必阅读前面的所有行,只需跳到该行即可。

回答by khmarbaise

Just simply read line by line first and count the line numbers and start getting the contents you need at the line position you mentioned.

只需简单地首先逐行阅读并计算行号,然后在您提到的行位置开始获取您需要的内容。