开发者

How do I append to a file in Scala?

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.


There is no scala-specific IO implementation at the moment, although I understand one written by Jesse Eichar is in incubation. I'm not sure, to what extent this makes use of the new File (path) API in JDK7. Because of this, for now I would go with the simple Java:

val fw = new FileWriter("test.txt", true)
try {
  fw.write( /* your stuff */)
}
finally fw.close() 


There is a cleaner way — without using external dependencies:

import scala.tools.nsc.io.File

File("filename").writeAll("hello!") // or appendAll("hello!")

or

import scala.tools.nsc.io.Path

Path("/path/to/file").createFile().appendAll("hello!")

Update (November 2020) These APIs are stable (unlike claims in the comments). They have been around since my original answer in 2015 and they are still present in the latest release.


val fw = new FileWriter("test.txt", true) ; 
fw.write("This line appended to file!") ; 
fw.close()


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")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜