comphunter159 comphunter159 - 1 year ago 73
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();

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download