如何附加到 Scala 中的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6870145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:16:34  来源:igfitidea点击:

How do I append to a file in Scala?

scala

提问by deltanovember

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.

但我不确定如何充实实现。此处的另一个问题暗示了 Scala 2.9 的功能,但我找不到更多详细信息。

回答by oxbow_lakes

There is no scala-specific IO implementation at the moment, although I understand one written by Jesse Eicharis 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:

目前还没有特定于 scala 的 IO 实现,尽管我知道Jesse Eichar 编写的一个正在孵化中。我不确定这在多大程度上利用了 JDK7 中的新文件(路径)API。因此,现在我将使用简单的 Java:

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

回答by Javad Sadeqzadeh

The question is old, so are the answers. I find this way easier:

问题很老,答案也很旧。我发现这种方式更容易:

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

or

或者

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

or

或者

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

Of course for more conciseness, you can import the scala.tools.nsc.iopackage and avoid repeating it in your code. An advantage of using this package is that you do not have to add any external dependency/library (unlike scala.io.file (Scalax) or Apache Commons for example).

当然,为了更简洁,您可以导入scala.tools.nsc.io包并避免在代码中重复。使用此包的一个优点是您不必添加任何外部依赖项/库(例如不同于 scala.io.file ( Scalax) 或 Apache Commons)。

Credits: Garett Hall, see this.

致谢: Garett Hall,看到这个

回答by Shaunak

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