2011-07-29 40 views
17

我想寫出類似下面的如何附加到Scala中的文件?

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

的方法,但我不知道如何充實執行。這裏的另一個問題暗示了Scala 2.9的功能,但我無法找到更多細節。

+0

另請參閱第二個示例,以便在此追加:http://stackoverflow.com/a/5218279/243233 – Jus12

回答

31

雖然我知道one written by Jesse Eichar是在孵化,但目前沒有scala特定的IO實現。我不確定,這在多大程度上利用了JDK7中的新文件(路徑)API。正因爲如此,現在我會用簡單的Java:

val fw = new FileWriter("test.txt", true) 
try { 
    fw.write(/* your stuff */) 
} 
finally fw.close() 
4
val fw = new FileWriter("test.txt", true) ; 
fw.write("This line appended to file!") ; 
fw.close() 
10

問題是舊的,答案也是這樣。我覺得這是比較容易的方式:

scala.tools.nsc.io.File("filename").writeAll("hello world") 

scala.tools.nsc.io.File("filename").appendAll("hello world") 

scala.tools.nsc.io.Path("/path/to/file").createFile().appendAll("hello world") 

課程更簡潔,可以導入scala.tools.nsc.io包,避免在代碼中重複它。使用這個包的好處是你不必添加任何外部依賴/庫(不像scala.io.file(例如Scalax)或Apache Commons)。

Credits:Garett Hall,參見this

+0

這不是公開的API,可隨時刪除,因此,如果您的應用程序代碼中斷一天。 –

+0

從圖書館:注意:這個圖書館被認爲是實驗性的,不應該使用,除非你知道你在做什麼。 – soote