Skip to content

Commit bb36414

Browse files
committed
Added a method to append a string to a text file.
Also refactors the appendLines method to use the newly introduced function.
1 parent cc24866 commit bb36414

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

src/main/scala/introprog/IO.scala

Lines changed: 22 additions & 2 deletions
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
/**
@@ -49,6 +53,23 @@ object IO:
4953
def saveLines(lines: Seq[String], fileName: String, enc: String = "UTF-8"): Unit =
5054
saveString(lines.mkString("\n"), fileName, enc)
5155

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+
5273
/**
5374
* Appends `lines` to the text file `fileName` using encoding `enc`.
5475
*
@@ -57,8 +78,7 @@ object IO:
5778
* @param enc the encoding of the file.
5879
* */
5980
def appendLines(lines: Seq[String], fileName: String, enc: String = "UTF-8"): Unit =
60-
val newLines = loadLines(fileName, enc).appendedAll(lines)
61-
saveLines(newLines, fileName, enc)
81+
appendString(lines.mkString("\n"), fileName, enc)
6282

6383
/**
6484
* Load a serialized object from a binary file called `fileName`.

0 commit comments

Comments
 (0)