Skip to content

Commit

Permalink
Merge pull request #46 from trilleplay/issues/45
Browse files Browse the repository at this point in the history
introduce appendLines method in IO.
  • Loading branch information
bjornregnell authored Jun 11, 2024
2 parents 35a4d2f + b1481fa commit 0a2f802
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion src/main/scala/introprog/IO.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package introprog

import java.io.BufferedWriter
import java.io.FileWriter
import java.nio.charset.Charset

/** A module with input/output operations from/to the underlying file system. */
object IO:
/**
Expand Down Expand Up @@ -47,7 +51,34 @@ object IO:
* @param enc the encoding of the file.
* */
def saveLines(lines: Seq[String], fileName: String, enc: String = "UTF-8"): Unit =
saveString(lines.mkString("\n"), fileName, enc)
saveString(lines.mkString("\n") + "\n", fileName, enc)

/**
* Appends `string` to the text file `fileName` using encoding `enc`.
*
* @param text the text to be appended to the file.
* @param fileName the path of the file.
* @param enc the encoding of the file.
* */
def appendString(text: String, fileName: String, enc: String = "UTF-8"): Unit =
val f = new java.io.File(fileName);
require(!f.isDirectory(), "The file you're trying to write to can't be a directory.")
val w =
if f.exists() then
new BufferedWriter(new FileWriter(fileName, Charset.forName(enc), true))
else
new java.io.PrintWriter(f, enc)
try w.write(text) finally w.close()

/**
* Appends `lines` to the text file `fileName` using encoding `enc`.
*
* @param lines the lines to append to the file.
* @param fileName the path of the file.
* @param enc the encoding of the file.
* */
def appendLines(lines: Seq[String], fileName: String, enc: String = "UTF-8"): Unit =
appendString(lines.mkString("\n"), fileName, enc)

/**
* Load a serialized object from a binary file called `fileName`.
Expand Down

0 comments on commit 0a2f802

Please sign in to comment.