why does this code read an html file uncontinuously
I am using this code to read a file, when I do it with a for loop it works properly but when I use while loop it reads the first line, leaves the second line, reads the third line, and...
Code :
try {
while(mybuffer.readLine() != null){
data.add(mybuffer.readLine());
System.out.println(data.elementAt(i));
i++;
}
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();}
}
}
Re: why does this code read an html file uncontinuously
Based on the assumption myBuff is a Reader (aka BufferedReader), every time you call readLine it reads the line and moves the pointer to the next, and as is the while loop skips over every other line because you do not keep the readLine data in memory...one workaround:
Code :
String line = null;
while ( ( line = myBuff.readLine() ) != null ){//store the readLine data in memory
//use the data in memory to add to your data object
}
Re: why does this code read an html file uncontinuously
but why it works with for loop without saving in memory. the code below works properly.
try {
for(int j =0; j<250; j++){
data.add(mybuffer.readLine());
System.out.println(data.elementAt(i));
i++;
}
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();}
}
Re: why does this code read an html file uncontinuously
Quote:
Originally Posted by
nasi
but why it works with for loop without saving in memory. the code below works properly.
Look closely at your original while code - every call to readLine moves the pointer in the file forward to the next line
Code :
while ( myBuffer.readLine() != null ){///reads line and moves the pointer forward (lines 1, 3, 5...)
data.add(mybuffer.readLine());//reads and stores the line (lines 2, 4, 6...)
}
Your for loop only calls readLine() a single time per loop, as opposed to the original while loop where it is called twice per loop
Re: why does this code read an html file uncontinuously
ohhhhhhhhh, I got it. thank you very much.
Best wishes