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.
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.
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.
You could do this:
Iterator .continually (input.read) .takeWhile (-1 !=) .foreach (output.write)
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()
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