summarized duplicate code in a new method writeFileToPath