How do I append to a file in Scala?

Viewed 34591

I would like to write a method similar to the following

def appendFile(fileName: String, line: String) = {
}

But I'm not sure how to flesh out the implementation. Another question on here alludes to Scala 2.9 capabilities but I could not find further details.

4 Answers

os-lib is the best option for Scala filesystem operations like appending to a file.

Here's how to append "hear me moo" to a file:

os.write.append(os.pwd/"whatever"/"file1.txt", "\nhear me moo")

os-lib is the best option for filesystem operations because it provides a unified API for all the common functions and also provides a clean API for paths. The Java APIs for filesystems require you to waste brainpower on low level details and force you to import a lot of code.

Here's a full example that creates a directory, creates a file, and then appends to the file if you'd like to experiment on your local machine:

os.makeDir(os.pwd/"whatever")
os.write(os.pwd/"whatever"/"file1.txt", "hi there")
os.write.append(os.pwd/"whatever"/"file1.txt", "\nhear me moo")
Related