The problem here is you need to set the focus of the scanner class reference pointer again to the start of the file and start comparing again.Because of this some of the rows are getting missed in the output file.
For getting the focus to the start of the file create a scanner reference freshly when you are entering the "while" loop.