Scala: write string to file in one statement

后端 未结 14 1171
星月不相逢
星月不相逢 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
    
    0 讨论(0)
  • 2020-11-29 17:37

    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!")
    
    0 讨论(0)
  • 2020-11-29 17:38

    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.

    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"))
    
    0 讨论(0)
  • 2020-11-29 17:39

    A concise one line:

    import java.io.PrintWriter
    new PrintWriter("filename") { write("file contents"); close }
    
    0 讨论(0)
  • 2020-11-29 17:43
    import sys.process._
    "echo hello world" #> new java.io.File("/tmp/example.txt") !
    
    0 讨论(0)
  • 2020-11-29 17:43

    UPDATE: I have since created a more effective solution upon which I have elaborated here: https://stackoverflow.com/a/34277491/501113

    I find myself working more and more in the Scala Worksheet within the Scala IDE for Eclipse (and I believe there is something equivalent in IntelliJ IDEA). Anyway, I need to be able to do a one-liner to output some of the contents as I get the "Output exceeds cutoff limit." message if I am doing anything significant, especially with the Scala collections.

    I came up with a one-liner I insert into the top of each new Scala Worksheet to simplify this (and so I don't have to do the whole external library import exercise for a very simple need). If you are a stickler and notice that it is technically two lines, it's only to make it more readable in this forum. It is a single line in my Scala Worksheet.

    def printToFile(content: String, location: String = "C:/Users/jtdoe/Desktop/WorkSheet.txt") =
      Some(new java.io.PrintWriter(location)).foreach{f => try{f.write(content)}finally{f.close}}
    

    And the usage is simply:

    printToFile("A fancy test string\ncontaining newlines\nOMG!\n")
    

    This allows me to optionally provide the file name should I want to have additional files beyond the default (which completely overwrites the file each time the method is called).

    So, the second usage is simply:

    printToFile("A fancy test string\ncontaining newlines\nOMG!\n", "C:/Users/jtdoe/Desktop/WorkSheet.txt")
    

    Enjoy!

    0 讨论(0)
提交回复
热议问题