comphunter159 comphunter159 - 1 month ago 5x
Java Question

java count the lines in a file and be able to read them later

I am trying to count the lines in a file to set a specified loop duration so that I can read the lines in the same file to extract the data.

I have tried do-while loops and while loops and the mistake that I keep seeing is that the program reads a line and then when I need the data from that line it reads the next line instead

while(in.readLine() != null){
name = in.readLine();
if (name != null && name.contains("Name: ")){
type = in.readLine();


Java will read the next line from the file every time you call readLine(). You only want to call it one time in the loop and store the value that's returned.

while ((line = in.readLine()) != null)...
    // use line inside the loop instead of calling readLine() again