javafilescalainputstreamlift

Is there a nice, safe, quick way to write an InputStream to a File in Scala?


Specifically, I'm saving a file upload to local file in a Lift web app.


Solution

  • If it's a text file, and you want to limit yourself to Scala and Java, then using scala.io.Source to do the reading is probably the fastest--it's not built in, but easy to write:

    def inputToFile(is: java.io.InputStream, f: java.io.File) {
      val in = scala.io.Source.fromInputStream(is)
      val out = new java.io.PrintWriter(f)
      try { in.getLines().foreach(out.println(_)) }
      finally { out.close }
    }
    

    But if you need other libraries anyway, you can make your life even easier by using them (as Michel illustrates).

    (P.S.--in Scala 2.7, getLines should not have a () after it.)

    (P.P.S.--in old versions of Scala, getLines did not remove the newline, so you need to print instead of println.)