Skip to content

Commit 0a2f802

Browse files
authored
Merge pull request #46 from trilleplay/issues/45
introduce appendLines method in IO.
2 parents 35a4d2f + b1481fa commit 0a2f802

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/main/scala/introprog/IO.scala

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
package introprog
22

3+
import java.io.BufferedWriter
4+
import java.io.FileWriter
5+
import java.nio.charset.Charset
6+
37
/** A module with input/output operations from/to the underlying file system. */
48
object IO:
59
/**
@@ -47,7 +51,34 @@ object IO:
4751
* @param enc the encoding of the file.
4852
* */
4953
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)
5182

5283
/**
5384
* Load a serialized object from a binary file called `fileName`.

0 commit comments

Comments
 (0)