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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14753153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:56:30  来源:igfitidea点击:

How do you convert an InputStream to a base64 string in Scala?

scala

提问by Dax Fohl

Trying to pull an image off of Amazon S3 (returns S3ObjectInputStream) and send it to the mandrill email api(takes a base64-encoded string). How can this be done in Scala?

尝试从 Amazon S3 中提取图像(返回S3ObjectInputStream)并将其发送到mandrill 电子邮件 API(采用 base64 编码的字符串)。这如何在 Scala 中完成?

回答by Dax Fohl

I also managed to do it just using the Apache commons; not sure which approach is better, but figured I'd leave this answer for the record:

我还设法仅使用 Apache 公共资源来做到这一点;不确定哪种方法更好,但我想我会把这个答案留作记录:

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)

回答by Lomig Mégard

Here is one solution, there are probably others more efficient.

这是一种解决方案,可能还有其他更有效的解决方案。

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)

You could (and should) also replace the sun.miscencoder by the apache commons Base64for a better compatibility.

您也可以(并且应该)用sun.miscapache commons Base64替换编码器以获得更好的兼容性。

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

回答by Mark Lister

Here's a simple encoder/decoderI wrote that you can include as source. So, no external dependencies.

这是我编写的一个简单的编码器/解码器,您可以将其包含为源。所以,没有外部依赖。

The interface is a bit more scala-esque:

界面有点像 Scala 风格:

import io.github.marklister.base64.Base64._ // Same as Lomig Mégard's answer val b64 = bytes.toBase64

import io.github.marklister.base64.Base64._ // Same as Lomig Mégard's answer val b64 = bytes.toBase64