-1

For example I want to read a text file from line number 20056 until line 1159450 and outputs it into the output window but I do not know how to do so as the method line.readline() starts with the first line.

This is my code:

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();

How do I print only from line 20056 until line 1159450 and outputs it into the output window?

dur
  • 15,689
  • 25
  • 79
  • 125

2 Answers2

1
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();
0

(Posted solution on behalf of the OP).

I just need to remove the first while loop.

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();

Credit to Jay Hamilton.

halfer
  • 19,824
  • 17
  • 99
  • 186