Java - 方法 encodeBase64
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29887351/
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
Java - The method encodeBase64
提问by Oti Na Nai
I have a String String x = "Sample text";
and I want to print the base64 encryption of it. As numerous examples mention, I use:
我有一个字符串String x = "Sample text";
,我想打印它的 base64 加密。正如许多例子所提到的,我使用:
byte[] encodedBytes = Base64.encodeBase64(x.getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
But this gives me The method encodeBase64(byte[]) is undefined for the type Base64
... Why is that?
但这给了我The method encodeBase64(byte[]) is undefined for the type Base64
......为什么会这样?
采纳答案by Anubian Noob
The encode
method is in the Base64.Encoder
class that you can get by running Base64.getEncoder()
.
该encode
方法在Base64.Encoder
您可以通过运行获得的类中Base64.getEncoder()
。
byte[] encodedBytes = Base64.getEncoder().encode(x.getBytes());
Similarly, to decode:
同样,解码:
String originalString = new String(Base64.getDecoder().decode(encodedBytes));
Check out the Base64
javadocsfor more info.
检查出的Base64
的javadoc获得更多信息。
回答by Colton Rushton
You could also use:
您还可以使用:
byte[] originalString = Base64.getDecoder().decode(encodedBytes);
to decode (this is what I used in a Base64 encoder/decoder applet I recently wrote)
解码(这是我在最近编写的 Base64 编码器/解码器小程序中使用的)
回答by Maarten Bodewes
Instead of rewriting the code you should simply include the Apache commons codec module into your classpath. This has the exact method signature, Base64.encodeBase64(byte[])
. And yes, just hitting "encodeBase64" in an internet search should be enough.
您应该简单地将 Apache 公共编解码器模块包含到您的类路径中,而不是重写代码。这具有确切的方法签名,Base64.encodeBase64(byte[])
. 是的,只需在互联网搜索中点击“encodeBase64”就足够了。
Note that your project may use other functionality from that same codecs package. So you should always first try and find the modules / libraries used by a project before you start replacing the code. And sometimes there are subtle differences between implementations, which could make the project fail in the right circumstances.
请注意,您的项目可能会使用同一编解码器包中的其他功能。因此,在开始替换代码之前,您应该始终首先尝试找到项目使用的模块/库。有时,实现之间存在细微的差异,这可能会使项目在正确的情况下失败。
That said, the code in the question does of course not make sense. You could use encodeBase64String
to directly convert to String
without having to convert to bytes and then to String
. And for newer level API's there is indeed the java.util.Base64
class, as mentioned in the other answer. Finally - and more importantly - if x
already contains a string, why would you base 64 encode it?
也就是说,问题中的代码当然没有意义。您可以使用encodeBase64String
直接转换为 ,String
而无需先转换为字节然后再转换为String
. 对于较新级别的 API,确实有java.util.Base64
该类,如另一个答案中所述。最后 - 更重要的是 - 如果x
已经包含一个字符串,为什么要对它进行 base 64 编码?