How to extract exact lines of text from a text file using line numbers in java? [closed]

StackOverflow https://stackoverflow.com/questions/19001802

  •  29-06-2022
  •  | 
  •  

Question

How to extract exact lines of text from a text file using line numbers in JAVA? For example i have a 1000 lines in a example.txt file from which i want to extract line numbers 100 - 150 to another report.txt file.

Was it helpful?

Solution

Try this,

while ((input = bufferedReader.readLine()) != null)
{
  count ++; // use a counter variable
  if (count >= fromLineNumber && count <= endLineNumber)
    {
       // process
       if(counter == endLineNumber) // break the loop while you reach the endLineNumber
        {
           break;
        }
    }
}

OTHER TIPS

You can have a simple solution by iterating using bufferedreader.readline() ignoring the first unneeded, and then write the needed ones to the new file.

Try following.

 File file = new File("pathto your file");
    int readStart = 100;
    int readEnd = 150;
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    int currentLineNumber = 0;
    while ((((line = br.readLine()) != null)&& (currentLineNumber <= readStart))){
        currentLineNumber = currentLineNumber + 1;
    }
    while (((line = br.readLine()) != null)
            && (currentLineNumber >= readStart && currentLineNumber <= readEnd)) {
        // process the line.
        currentLineNumber = currentLineNumber + 1;
    }
    br.close();

Hope it helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top