Read text file in Java

会有一股神秘感。 提交于 2019-11-28 09:12:32

问题


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.


回答1:


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;
}



回答2:


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

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).




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/2714385/read-text-file-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!