首页 > 解决方案 > 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

标签: javabase64tobase64string

解决方案


您忘记将字符编码传递给 String 构造函数,因此它使用平台默认字符编码创建字符串。利用:

return new String(actualByte, utfType);

推荐阅读