Specifically, I'm saving a file upload to local file in a Lift web app.
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.
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.
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.
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 Path
s or InputStream
s. 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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With