Scala: write string to file in one statement

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

    If you like Groovy syntax, you can use the Pimp-My-Library design pattern to bring it to 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
    

提交回复
热议问题