Scala: write string to file in one statement

后端 未结 14 1173
星月不相逢
星月不相逢 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 18:00

    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()
    
    0 讨论(0)
  • 2020-11-29 18:04

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

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

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

    Some(new PrintWriter("filename")).foreach{p => p.write("hello world"); p.close}
    
    0 讨论(0)
提交回复
热议问题