Scala:在一个语句中将字符串写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6879427/
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:59  来源:igfitidea点击:

Scala: write string to file in one statement

scalascala-2.9

提问by smartnut007

For reading files in Scala, there is

对于在 Scala 中读取文件,有

Source.fromFile("file.txt").mkString

Is there an equivalent and concise way to write a string to file?

是否有等效且简洁的方法将字符串写入文件?

Most languages support something like that. My favorite is Groovy:

大多数语言都支持类似的东西。我最喜欢的是 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.

我想将代码用于从一行到一小页代码的程序。必须使用自己的库在这里没有意义。我希望有一种现代语言能让我方便地向文件中写入内容。

There are posts similar to this, but they don't answer my exact question or are focused on older Scala versions.

有与此类似的帖子,但它们没有回答我的确切问题或专注于较旧的 Scala 版本。

For example:

例如:

采纳答案by LRLucena

A concise one line:

简洁的一行:

import java.io.PrintWriter
new PrintWriter("filename") { write("file contents"); close }

回答by Vladimir Matveev

It is strange that no one had suggested NIO.2 operations (available since Java 7):

奇怪的是,没有人建议过 NIO.2 操作(自 Java 7 开始可用):

import java.nio.file.{Paths, Files}
import java.nio.charset.StandardCharsets

Files.write(Paths.get("file.txt"), "file contents".getBytes(StandardCharsets.UTF_8))

I think this is by far the simplest and easiest and most idiomatic way, and it does not need any dependencies sans Java itself.

我认为这是迄今为止最简单、最简单和最惯用的方法,它不需要任何依赖项,没有 Java 本身。

回答by Garrett Hall

Here is a concise one-liner using reflect.io.file, this works with Scala 2.12:

这是使用reflect.io.file的简洁单行,这适用于Scala 2.12:

reflect.io.File("filename").writeAll("hello world")

Alternatively, if you want to use the Java libraries you can do this hack:

或者,如果您想使用 Java 库,您可以执行以下操作:

Some(new PrintWriter("filename")).foreach{p => p.write("hello world"); p.close}

回答by paradigmatic

If you like Groovy syntax, you can use the Pimp-My-Librarydesign pattern to bring it to Scala:

如果您喜欢 Groovy 语法,可以使用Pimp-My-Library设计模式将其引入 Scala:

import java.io._
import scala.io._

class RichFile( file: File ) {

  def text = Source.fromFile( file )(Codec.UTF8).mkString

  def text_=( s: String ) {
    val out = new PrintWriter( file , "UTF-8")
    try{ out.print( s ) }
    finally{ out.close }
  }
}

object RichFile {

  implicit def enrichFile( file: File ) = new RichFile( file )

}

It will work as expected:

它将按预期工作:

scala> import RichFile.enrichFile
import RichFile.enrichFile

scala> val f = new File("/tmp/example.txt")
f: java.io.File = /tmp/example.txt

scala> f.text = "hello world"

scala> f.text
res1: String = 
"hello world

回答by xiefei

import sys.process._
"echo hello world" #> new java.io.File("/tmp/example.txt") !

回答by pathikrit

A micro library I wrote: https://github.com/pathikrit/better-files

我写的一个微库:https: //github.com/pathikrit/better-files

file.write("Hi!")

or

或者

file << "Hi!"

回答by RyuuGan

You can easily use Apache File Utils. Look at function writeStringToFile. We use this library in our projects.

您可以轻松使用Apache File Utils。看功能writeStringToFile。我们在我们的项目中使用这个库。

回答by Luigi Sgro

This is concise enough, I guess:

这足够简洁,我想:

scala> import java.io._
import java.io._

scala> val w = new BufferedWriter(new FileWriter("output.txt"))
w: java.io.BufferedWriter = java.io.BufferedWriter@44ba4f

scala> w.write("Alice\r\nBob\r\nCharlie\r\n")

scala> w.close()

回答by Dibbeke

One also has this format, which is both concise and the underlying library is beautifully written (see the source code):

一个也有这种格式,既简洁又底层库写得很漂亮(见源码):

import scalax.io.Codec
import scalax.io.JavaConverters._

implicit val codec = Codec.UTF8

new java.io.File("hi-file.txt").asOutput.write("I'm a hi file! ... Really!")

回答by stefan.schwetschke

You can do this with a mix of Java and Scala libraries. You will have full control over the character encoding. But unfortunately, the file handles will not be closed properly.

您可以混合使用 Java 和 Scala 库来做到这一点。您将完全控制字符编码。但不幸的是,文件句柄将无法正确关闭。

scala> import java.io.ByteArrayInputStream
import java.io.ByteArrayInputStream

scala> import java.io.FileOutputStream
import java.io.FileOutputStream

scala> BasicIO.transferFully(new ByteArrayInputStream("test".getBytes("UTF-8")), new FileOutputStream("test.txt"))