|
1 | 1 | package introprog |
2 | 2 |
|
| 3 | +import java.io.BufferedWriter |
| 4 | +import java.io.FileWriter |
| 5 | +import java.nio.charset.Charset |
| 6 | + |
3 | 7 | /** A module with input/output operations from/to the underlying file system. */ |
4 | 8 | object IO: |
5 | 9 | /** |
@@ -47,7 +51,34 @@ object IO: |
47 | 51 | * @param enc the encoding of the file. |
48 | 52 | * */ |
49 | 53 | def saveLines(lines: Seq[String], fileName: String, enc: String = "UTF-8"): Unit = |
50 | | - saveString(lines.mkString("\n"), fileName, enc) |
| 54 | + saveString(lines.mkString("\n") + "\n", fileName, enc) |
| 55 | + |
| 56 | + /** |
| 57 | + * Appends `string` to the text file `fileName` using encoding `enc`. |
| 58 | + * |
| 59 | + * @param text the text to be appended to the file. |
| 60 | + * @param fileName the path of the file. |
| 61 | + * @param enc the encoding of the file. |
| 62 | + * */ |
| 63 | + def appendString(text: String, fileName: String, enc: String = "UTF-8"): Unit = |
| 64 | + val f = new java.io.File(fileName); |
| 65 | + require(!f.isDirectory(), "The file you're trying to write to can't be a directory.") |
| 66 | + val w = |
| 67 | + if f.exists() then |
| 68 | + new BufferedWriter(new FileWriter(fileName, Charset.forName(enc), true)) |
| 69 | + else |
| 70 | + new java.io.PrintWriter(f, enc) |
| 71 | + try w.write(text) finally w.close() |
| 72 | + |
| 73 | + /** |
| 74 | + * Appends `lines` to the text file `fileName` using encoding `enc`. |
| 75 | + * |
| 76 | + * @param lines the lines to append to the file. |
| 77 | + * @param fileName the path of the file. |
| 78 | + * @param enc the encoding of the file. |
| 79 | + * */ |
| 80 | + def appendLines(lines: Seq[String], fileName: String, enc: String = "UTF-8"): Unit = |
| 81 | + appendString(lines.mkString("\n"), fileName, enc) |
51 | 82 |
|
52 | 83 | /** |
53 | 84 | * Load a serialized object from a binary file called `fileName`. |
|
0 commit comments