Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 950
pr1001 Avatar asked May 06 '10 16:05

pr1001


People also ask

How do you create an input stream object to read a file?

Java FileInputStream constructorsFileInputStream(File file) — creates a file input stream to read from a File object. FileInputStream(String name) — creates a file input stream to read from the specified file name. FileInputStream(FileDescriptor fdObj) — creates a file input read from the specified file descriptor.

What is the difference between InputStream and FileInputStream?

There is no real difference. FileInputStream extends InputStream , and so you can assign an InputStream object to be a FileInputStream object. In the end, it's the same object, so the same operations will happen. This behavior is called Polymorphism and is very important in Object-Oriented Programming.

Do I need to close InputStream?

You do need to close the input Stream, because the stream returned by the method you mention is actually FileInputStream or some other subclass of InputStream that holds a handle for a file. If you do not close this stream you have resource leakage.


2 Answers

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.

like image 107
notan3xit Avatar answered Sep 20 '22 18:09

notan3xit


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

like image 44
Rex Kerr Avatar answered Sep 18 '22 18:09

Rex Kerr