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

With Java 7 or later you can use Files from the new File I/O:

Files.copy(from, to)

where from and to can be Paths or InputStreams. This way, you can even use it to conveniently extract resources from applications packed in a jar.


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.)


I don't know about any Scala specific API, but since Scala is fully compatible to Java you can use any other library like Apache Commons IO and Apache Commons FileUpload.

Here is some example code (untested):

//using Commons IO:
val is = ... //input stream you want to write to a file
val os = new FileOutputStream("out.txt")
org.apache.commons.io.IOUtils.copy(is, os)
os.close()

//using Commons FileUpload
import javax.servlet.http.HttpServletRequest
import org.apache.commons.fileupload.{FileItemFactory, FileItem}
import apache.commons.fileupload.disk.DiskFileItemFactory
import org.apache.commons.fileupload.servlet.ServletFileUpload
val request: HttpServletRequest = ... //your HTTP request
val factory: FileItemFactory = new DiskFileItemFactory()
val upload = new ServletFileUpload(factory)
val items = upload.parseRequest(request).asInstanceOf[java.util.List[FileItem]]
for (item <- items) item.write(new File(item.getName))