我有一个用 Base64 编码的字符串:
eJx9xEERACAIBMBKJyKDcTzR_hEsgOxjAcBQFVVNvi3qEsrRnWXwbhHOmzWnctPHPVkPu-4vBQ==
我如何用 Scala 语言解码它?
我尝试使用:
val bytes1 = new sun.misc.BASE64Decoder().decodeBuffer(compressed_code_string)
但是当我将字节数组与我用 Python 语言生成的正确字节数组进行比较时,出现了错误。这是我在 python 中使用的命令:
import base64
base64.urlsafe_b64decode(compressed_code_string)
Scala 中的字节数组是:
(120, -100, 125, -60, 65, 17, 0, 32, 8, 4, -64, 74, 39, 34, -125, 113, 60, -47, -2 , 17, 44, -128, -20, 99, 1, -64, 80, 21, 85, 77, -66, 45, -22, 18, -54, -47, -99, 101, -16, 110、17、-50、-101、53、-89、114、-45、-57、61、89、15、-69、-2、47、5)
而在python中生成的是:
(120, -100, 125, -60, 65, 17, 0, 32, 8, 4, -64, 74, 39, 34, -125, 113, 60, -47, -2 , 17, 44, -128, -20, 99, 1, -64, 80, 21, 85, 77, -66, 45, -22, 18, -54, -47, -99, 101, -16, 110、17、-50、-101、53、-89、114、-45、-57、61、89、15、-69、-18、47、5)
注意数组末尾有一处不同
最佳答案
在 Scala 中,使用 Java API 将字符串编码为 Base64 并解码回原始字符串:
import java.util.Base64
import java.nio.charset.StandardCharsets
scala> val bytes = "foo".getBytes(StandardCharsets.UTF_8)
bytes: Array[Byte] = Array(102, 111, 111)
scala> val encoded = Base64.getEncoder().encodeToString(bytes)
encoded: String = Zm9v
scala> val decoded = Base64.getDecoder().decode(encoded)
decoded: Array[Byte] = Array(102, 111, 111)
scala> val str = new String(decoded, StandardCharsets.UTF_8)
str: String = foo
关于java - 如何在 Scala 或 Java 中解码 Base64 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21318601/