Scala: write string to file in one statement

后端 未结 14 1217
星月不相逢
星月不相逢 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:46

    I know it's not one line, but it solves the safety issues as far as I can tell;

    // This possibly creates a FileWriter, but maybe not
    val writer = Try(new FileWriter(new File("filename")))
    // If it did, we use it to write the data and return it again
    // If it didn't we skip the map and print the exception and return the original, just in-case it was actually .write() that failed
    // Then we close the file
    writer.map(w => {w.write("data"); w}).recoverWith{case e => {e.printStackTrace(); writer}}.map(_.close)
    

    If you didn't care about the exception handling then you can write

    writer.map(w => {w.writer("data"); w}).recoverWith{case _ => writer}.map(_.close)
    

提交回复
热议问题