Skip to content

Commit 88415df

Browse files
authored
Merge pull request #53 from JohanbcEkberg/master
Check if file already exists and if is directory
2 parents ef9716d + bfbfb5f commit 88415df

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

src/main/scala/introprog/IO.scala

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,16 @@ object IO:
3737
* @param text the text to be written to the file.
3838
* @param fileName the path of the file.
3939
* @param enc the encoding of the file.
40+
* @param isOverwrite should the file be overwritten if it already exists
4041
* */
41-
def saveString(text: String, fileName: String, enc: String = "UTF-8"): Unit =
42+
def saveString(text: String, fileName: String, enc: String = "UTF-8", isOverwrite: Boolean = false): Unit =
4243
val f = new java.io.File(fileName)
44+
45+
if !isOverwrite then
46+
require(!f.exists(), s"The file $fileName already exists. To overwrite it, set isOverwrite=true.")
47+
48+
require(!f.isDirectory(), "The file you're trying to write to can't be a directory.")
49+
4350
val pw = new java.io.PrintWriter(f, enc)
4451
try pw.write(text) finally pw.close()
4552

0 commit comments

Comments
 (0)