Fixed file writing issue.
It was a stupid mistake :D I was closing the file in the loop!
Just moved writer.close() call later beyond the loops. :)