java - Java中的Base64 UTF-32解码无法按预期工作
问题描述
我有 Base64 UTF-32 编码的字符串,而解码它带有空格。我正在使用 org.apache.commons.codec 库。
对于使用以下代码进行编码并按预期正常工作
public static String encodeBase64(String encodeString,String utfType){
try {
return new String(Base64.encodeBase64String(encodeString.getBytes(utfType)));
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
System.out.println(encodeBase64("This is UTF-32 encoading test","UTF-32"));
这给了我 Base64 编码的字符串
AAAAVAAAAGgAAABpAAAAcwAAACAAAABpAAAAcwAAACAAAABVAAAAVAAAAEYAAAAtAAAAMwAAADIAAAAgAAAAZQAAAG4AAABjAAAAbwAAAGEAAABkAAAAaQAAAG4AAABnAAAAIAAAAHQAAABlAAAAcwAAAHQ=
我想解码上面的字符串
public static String decodeBase64(String decodeString,String utfType){
try {
byte[] actualByte = java.util.Base64.getDecoder() .decode(decodeString);
return new String(actualByte);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
System.out.println(decodeBase64("AAAAVAAAAGgAAABpAAAAcwAAACAAAABpAAAAcwAAACAAAABVAAAAVAAAAEYAAAAtAAAAMwAAADIAAAAgAAAAZQAAAG4AAABjAAAAbwAAAGEAAABkAAAAaQAAAG4AAABnAAAAIAAAAHQAAABlAAAAcwAAAHQ=","UTF-32"));
收到的输出如下,不正确
T h i s i s U T F - 3 2 e n c o a
d i n g t e s t
如何在解码后将其作为原始字符串如下值 这是 UTF-32 编码测试","UTF-32
解决方案
您忘记将字符编码传递给 String 构造函数,因此它使用平台默认字符编码创建字符串。利用:
return new String(actualByte, utfType);
推荐阅读
- javascript - Vue 3 将组件附加到 DOM:最佳实践
- r - R中的filter()不在for循环中打印?
- ios - performSegueWithIdentifier 在目标 c 中工作,但日志中显示奇怪的警告
- rendering - Blender Cycles 像 Eevee 一样渲染
- python - 即使我限制了最大和最小窗口大小,当我将 Tkinter 窗口拖到顶部时,它也会继续扩展
- django - Django:用户与用户配置文件
- azure-devops - 使用 AZ 管道和具有 .net 5 AZ 功能后端的静态 Web 应用程序时如何修复 SDK 错误
- python - Python,AWS S3:如何使用 jsons 读取文件
- azure - 是否可以组合多个 Application Insights 应用程序映射?
- angular - 如何在 TypeScript 文件中将 >= 的值更改为 ascii 字符