如何在下面的代码中使用scala-arm
以便自动发布inputStream
?
def inflate(data: Array[Byte]): Array[Byte] = {
val inputStream = new InflaterInputStream(new ByteArrayInputStream(data), new Inflater)
Stream.continually(inputStream.read).takeWhile(-1 !=).map(_.toByte).toArray
}
我试过这样的事情...但是当然最后一个语句失败了,因为方法 toArray
不是 resource.ExtractableManagedResource
的成员:
def inflate(data: Array[Byte]): Array[Byte] = {
val outputStream = for {
inputStream <- managed(new InflaterInputStream(new ByteArrayInputStream(data), new Inflater))
} yield Stream.continually(inputStream.read).takeWhile(-1 !=).map(_.toByte)
outputStream.toArray
}
以下是如何使用scala-arm
管理输出流的工作示例:
def deflate(data: Array[Byte]) = {
val outputStream = new ByteArrayOutputStream
for (deflaterOutputStream <- managed(new DeflaterOutputStream(outputStream, new Deflater))) {
deflaterOutputStream.write(data)
}
outputStream.toByteArray
}
有没有一种更简洁、面向 scala 的方式来处理托管资源和scala-arm
(或scalax.io
)?
尝试使用 scalax.io 作为 scala-arm 的替代方法,以返回一个将延迟从流中读取的Traversable[Byte]
def inflate(data: Array[Byte]): Traversable[Byte] = {
val inflater = new InflaterInputStream(new ByteArrayInputStream(data), new Inflater)
Resource.fromInputStream(inflater).bytes
}
或者,您可以将此Traversable[Byte]
转换为Array[Byte]
,该会将整个InputStream
读取到内存中:
def inflate(data: Array[Byte]): Array[Byte] = {
val inflater = new InflaterInputStream(new ByteArrayInputStream(data), new Inflater)
Resource.fromInputStream(inflater).bytes.toArray
}
以下是如何使用Deflater
:
def deflate(data: Array[Byte]) = {
val outputStream = new ByteArrayOutputStream
Resource.fromOutputStream(new DeflaterOutputStream(outputStream, new Deflater)).write(data)
outputStream.toByteArray
}