Reading a text file in Java

I have a text file. I would like to get content from one line to another. For example, a file might be 200K lines. I want to read the contents from line 78 to line 2735. Since the file can be very large, I do not want to read all the content in memory.

+2
source share
4 answers

Here the possible solution begins:

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

Use BufferedReader.readLine () and count the lines. You will only save the size of the buffer and the current line in memory.

And no, it's impossible to go to line 3412 without reading the entire file to this point (unless your lines have a fixed size).

+12

Just just read line by line first and count the line numbers and start getting the content you need in the line you specify.

0
source

I would suggest using RandomAccessFile, this class allows you to go to a specific place in the file. Therefore, if you want to read the last line of a file, you do not need to read all the previous lines, you can simply go to that line.

0
source

Source: https://habr.com/ru/post/1758580/


All Articles