Scala:在一个语句中将字符串写入文件 [英] Scala: write string to file in one statement
本文介绍了Scala:在一个语句中将字符串写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Scala中读取文件,有
For reading files in Scala, there is
Source.fromFile("file.txt").mkString
是否有等效且简洁的方法将字符串写入文件?
Is there an equivalent and concise way to write a string to file?
大多数语言都支持类似的东西.我最喜欢的是 Groovy:
Most languages support something like that. My favorite is Groovy:
def f = new File("file.txt")
// Read
def s = f.text
// Write
f.text = "file contents"
我想将代码用于从一行到一小页代码的程序.必须使用自己的库在这里没有意义.我希望有一种现代语言能让我方便地向文件中写入内容.
I'd like to use the code for programs ranging from a single line to a short page of code. Having to use your own library doesn't make sense here. I expect a modern language to let me write something to a file conveniently.
有类似的帖子,但它们没有回答我的确切问题,或者专注于较旧的 Scala 版本.
There are posts similar to this, but they don't answer my exact question or are focused on older Scala versions.
例如:
推荐答案
简洁的一行:
import java.io.PrintWriter
new PrintWriter("filename") { write("file contents"); close }
这篇关于Scala:在一个语句中将字符串写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文