Scala: write string to file in one statement

后端 未结 14 1193
星月不相逢
星月不相逢 2020-11-29 17:31

For reading files in Scala, there is

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

Is there an equivalent and concise way to write a string to fi

14条回答
  •  失恋的感觉
    2020-11-29 17:59

    It is strange that no one had suggested NIO.2 operations (available since 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.

提交回复
热议问题