-1

Hey there im trying to read a .txt file line by line but somehow it only reads every second line..

try {
    FileReader fr = new FileReader("file.txt");
    BufferedReader br = new BufferedReader(fr);
    while (br.readLine() != null){
        println(br.readLine());     //method to print the line
    }
}catch (FileNotFoundException e){}

This is what it should print:

stuff
stuff
stuff
more stuff
SAVED
LOADED
SAVED
LOADED

Instead it just prints this:

stuff
more stuff
LOADED
LOADED

I have no idea whats going on and could really use some help

mr.jogurt
  • 43
  • 8
  • 2
    Because you are calling `readLine()` twice, once in the loop check and once in the `println()`. – KevinO Apr 10 '18 at 14:42
  • possible duplicate of https://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java – Digao Apr 16 '18 at 20:16

1 Answers1

3

When calling br.readLine() you are already reading but your first call is just to make sure you have a return value which ist not null. Go with something like this:

String line;
while((line = br.readLine()) != null)
{
   println(line);
}
L.Spillner
  • 1,772
  • 10
  • 19