1) you could reuse the writeStringToFile() method that I was mentioning
2) I think it's better to have the lock done before opening the file