Scala: write string to file in one statement

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

提交回复
热议问题