From bfbfb5f5ac758f95e093542bc11134dc22be1c9d Mon Sep 17 00:00:00 2001 From: JohanBCEkberg Date: Fri, 19 Sep 2025 14:44:45 +0200 Subject: [PATCH] Check if file already exists and if is directory --- src/main/scala/introprog/IO.scala | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/scala/introprog/IO.scala b/src/main/scala/introprog/IO.scala index dd4e32a..352888f 100644 --- a/src/main/scala/introprog/IO.scala +++ b/src/main/scala/introprog/IO.scala @@ -37,9 +37,16 @@ object IO: * @param text the text to be written to the file. * @param fileName the path of the file. * @param enc the encoding of the file. + * @param isOverwrite should the file be overwritten if it already exists * */ - def saveString(text: String, fileName: String, enc: String = "UTF-8"): Unit = + def saveString(text: String, fileName: String, enc: String = "UTF-8", isOverwrite: Boolean = false): Unit = val f = new java.io.File(fileName) + + if !isOverwrite then + require(!f.exists(), s"The file $fileName already exists. To overwrite it, set isOverwrite=true.") + + require(!f.isDirectory(), "The file you're trying to write to can't be a directory.") + val pw = new java.io.PrintWriter(f, enc) try pw.write(text) finally pw.close()