Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read a file to an InputStream then write it into an OutputStream in Scala?

Tags:

I'm trying to use basic Java code in Scala to read from a file and write to an OutputStream, but when I use the usual while( != -1 ) in Scala gives me a warning "comparing types of Unit and Int with != will always yield true".

The code is as follows:

    val file = this.cache.get(imageFileEntry).getValue().asInstanceOf[File]     response.setContentType( "image/%s".format( imageDescription.getFormat() ) )      val input = new BufferedInputStream( new FileInputStream( file ) )     val output = response.getOutputStream()      var read : Int = -1      while ( ( read = input.read ) != -1 ) {         output.write( read )     }      input.close()     output.flush() 

How am I supposed to write from an input stream to an output stream in Scala?

I'm mostly interested in a Scala-like solution.

like image 734
Maurício Linhares Avatar asked Aug 03 '11 14:08

Maurício Linhares


People also ask

How do you write InputStream to OutputStream?

transferTo() Method. In Java 9 or higher, you can use the InputStream. transferTo() method to copy data from InputStream to OutputStream . This method reads all bytes from this input stream and writes the bytes to the given output stream in the original order.

How do you write OutputStream?

Methods of OutputStreamwrite() - writes the specified byte to the output stream. write(byte[] array) - writes the bytes from the specified array to the output stream. flush() - forces to write all data present in output stream to the destination. close() - closes the output stream.


2 Answers

You could do this:

Iterator  .continually (input.read) .takeWhile (-1 !=) .foreach (output.write) 
like image 188
Daniel C. Sobral Avatar answered Oct 08 '22 02:10

Daniel C. Sobral


If this is slow:

Iterator  .continually (input.read) .takeWhile (-1 !=) .foreach (output.write) 

you can expand it:

val bytes = new Array[Byte](1024) //1024 bytes - Buffer size Iterator .continually (input.read(bytes)) .takeWhile (-1 !=) .foreach (read=>output.write(bytes,0,read)) output.close() 
like image 23
Yaroslav Avatar answered Oct 08 '22 04:10

Yaroslav