Harden writeFile, make sure the output stream is closed, consider also the case that the rename against an existing target might not work