如何在Scala中将InputStream转换为base64字符串?

如何在Scala中将InputStream转换为base64字符串?,scala,Scala,尝试从Amazon S3中提取图像(返回S3ObjectInputStream)并将其发送到(使用base64编码字符串)。在Scala中如何做到这一点?这里有一个解决方案,可能还有其他更有效的解决方案 val is = new ByteArrayInputStream(Array[Byte](1, 2, 3)) // replace by your InputStream val stream = Stream.continually(is.read).takeWhile(_ != -1).m

尝试从Amazon S3中提取图像(返回
S3ObjectInputStream
)并将其发送到(使用base64编码字符串)。在Scala中如何做到这一点?

这里有一个解决方案,可能还有其他更有效的解决方案

val is = new ByteArrayInputStream(Array[Byte](1, 2, 3)) // replace by your InputStream
val stream = Stream.continually(is.read).takeWhile(_ != -1).map(_.toByte)
val bytes = stream.toArray
val b64 = new sun.misc.BASE64Encoder().encode(bytes)
您还可以(也应该)用apache commons替换
sun.misc
编码器,以获得更好的兼容性

val b64 = org.apache.commons.codec.binary.Base64.encodeBase64(bytes)

我还使用ApacheCommons实现了这一点;不确定哪种方法更好,但我想我会把这个答案留作记录:

import org.apache.commons.codec.binary.Base64
import org.apache.commons.io.IOUtils

val bytes = IOUtils.toByteArray(stream)
val bytes64 = Base64.encodeBase64(bytes)
val content = new String(bytes64)
这是我写的一篇文章,你可以把它作为源代码。因此,没有外部依赖关系

界面更像scala:

import io.github.marklister.base64.base64_
//与Lomig Mégard的回答相同

val b64=bytes.toBase64

假设apache commons库可用,我认为您的答案更好。