如何从某一行读到某一行?

How do I read from a certain line until a certain line?

例如,我想从第 20056 行到第 1159450 行读取一个文本文件,并将其输出到输出 window 但我不知道如何这样做,因为方法 line.readline() 开始与第一行。

这是我的代码:

String line;
int currentLineNo = 1;
int startLine = 20056;//40930;
int endLine = 1159450;

FileReader file = new FileReader("yourfilepath");
BufferedReader reader = new BufferedReader(file);

PrintWriter writer = new PrintWriter("yourfilepath", "UTF-8");

while (currentLineNo < startLine) {
    currentLineNo++;
}

while(currentLineNo >= startLine && currentLineNo <= endLine) {
    // System.out.println(currentLineNo);
    line = reader.readLine();

    System.out.println(line);
    // writer.println(line);
    currentLineNo++;
}

reader.close();
writer.close();

如何只打印第 20056 行到第 1159450 行并将其输出到输出 window?

String line;
int currentLineNo = 1;
int startLine = 20056;//40930;
int endLine = 1159450;

FileReader file = new FileReader("yourfilepath");
BufferedReader reader = new BufferedReader(file);

PrintWriter writer = new PrintWriter("yourfilepath", "UTF-8");

while (currentLineNo <= endLine)
{
    line = reader.readLine();
    if(currentLineNo >= startLine && currentLineNo<=endLine) 
    {  System.out.println(line); }

    currentLineNo++;
}

reader.close();
writer.close();

(代表OP发布解决方案)。

我只需要删除第一个 while 循环。

String line;
    int currentLineNo = 1;
    int startLine = 20056;//40930;
    int endLine = 1159450;

    FileReader file = new FileReader("yourfilepath");
    BufferedReader reader = new BufferedReader(file);

    PrintWriter writer = new PrintWriter("yourfilepath", "UTF-8");

    while(currentLineNo<=endLine) 
    {
        line = reader.readLine();
        if(currentLineNo >= startLine && currentLineNo<=endLine) 
        {  System.out.println(line); }

        currentLineNo++;
    }

    reader.close();
    writer.close();

归功于 Jay Hamilton。