Java - encodeBase64 方法
Java - The method encodeBase64
我有一个字符串 String x = "Sample text";
,我想打印它的 base64 加密。正如许多例子提到的,我使用:
byte[] encodedBytes = Base64.encodeBase64(x.getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
但这给了我 The method encodeBase64(byte[]) is undefined for the type Base64
... 这是为什么?
encode
方法在Base64.Encoder
class里面可以通过运行Base64.getEncoder()
.
得到
byte[] encodedBytes = Base64.getEncoder().encode(x.getBytes());
同理,解码:
String originalString = new String(Base64.getDecoder().decode(encodedBytes));
查看 the Base64
javadocs 了解更多信息。
您还可以使用:
byte[] originalString = Base64.getDecoder().decode(encodedBytes);
解码(这是我最近写的一个Base64encoder/decoder小程序中使用的)
您无需重写代码,只需将 Apache 通用编解码器模块包含到您的 class 路径中即可。这具有确切的方法签名,Base64.encodeBase64(byte[])
。是的,只需在互联网搜索中点击 "encodeBase64" 就足够了。
请注意,您的项目可能会使用同一编解码器包中的其他功能。因此,在开始替换代码之前,您应该始终首先尝试找到项目使用的模块/库。有时实现之间存在细微差别,这可能会使项目在适当的情况下失败。
也就是说,问题中的代码当然没有意义。您可以使用 encodeBase64String
直接转换为 String
,而无需转换为字节,然后再转换为 String
。对于较新的级别 API,确实有 java.util.Base64
class,如 中所述。最后 - 更重要的是 - 如果 x
已经包含一个字符串,为什么要对它进行 base 64 编码?
我有点解决了,但检查它是否有效
decode.setText(新字符串(Base64.decode(inputText.getText().toString(), Base64.DEFAULT)));
如果不起作用请告诉我
我有一个字符串 String x = "Sample text";
,我想打印它的 base64 加密。正如许多例子提到的,我使用:
byte[] encodedBytes = Base64.encodeBase64(x.getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
但这给了我 The method encodeBase64(byte[]) is undefined for the type Base64
... 这是为什么?
encode
方法在Base64.Encoder
class里面可以通过运行Base64.getEncoder()
.
byte[] encodedBytes = Base64.getEncoder().encode(x.getBytes());
同理,解码:
String originalString = new String(Base64.getDecoder().decode(encodedBytes));
查看 the Base64
javadocs 了解更多信息。
您还可以使用:
byte[] originalString = Base64.getDecoder().decode(encodedBytes);
解码(这是我最近写的一个Base64encoder/decoder小程序中使用的)
您无需重写代码,只需将 Apache 通用编解码器模块包含到您的 class 路径中即可。这具有确切的方法签名,Base64.encodeBase64(byte[])
。是的,只需在互联网搜索中点击 "encodeBase64" 就足够了。
请注意,您的项目可能会使用同一编解码器包中的其他功能。因此,在开始替换代码之前,您应该始终首先尝试找到项目使用的模块/库。有时实现之间存在细微差别,这可能会使项目在适当的情况下失败。
也就是说,问题中的代码当然没有意义。您可以使用 encodeBase64String
直接转换为 String
,而无需转换为字节,然后再转换为 String
。对于较新的级别 API,确实有 java.util.Base64
class,如 x
已经包含一个字符串,为什么要对它进行 base 64 编码?
我有点解决了,但检查它是否有效
decode.setText(新字符串(Base64.decode(inputText.getText().toString(), Base64.DEFAULT)));
如果不起作用请告诉我