简体   繁体   English

在 Java 中解码 Base64 字符串

[英]Decoding a Base64 string in Java

I'm trying to decode a simple Base64 string, but am unable to do so.我正在尝试解码一个简单的 Base64 字符串,但我无法这样做。 I'm currently using the org.apache.commons.codec.binary.Base64 package.我目前正在使用org.apache.commons.codec.binary.Base64包。

The test string I'm using is: abcdefg , encoded using PHP YWJjZGVmZw== .我使用的测试字符串是: abcdefg ,使用 PHP YWJjZGVmZw==编码。

This is the code I'm currently using:这是我目前使用的代码:

Base64 decoder = new Base64();
byte[] decodedBytes = decoder.decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n") ;   

The above code does not throw an error, but instead doesn't output the decoded string as expected.上面的代码不会抛出错误,而是不会按预期输出解码后的字符串。

Modify the package you're using:修改您正在使用的包:

import org.apache.commons.codec.binary.Base64;

And then use it like this:然后像这样使用它:

byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");

The following should work with the latest version of Apache common codec以下应该适用于最新版本的 Apache 通用编解码器

byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));

and for encoding和编码

byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));

If you don't want to use apache, you can use Java8:如果不想用apache,可以用Java8:

byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw=="); 
System.out.println(new String(decodedBytes) + "\n");

Commonly base64 it is used for images.通常 base64 用于图像。 if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):如果你想解码一个图像(在这个例子中是 jpg 与 org.apache.commons.codec.binary.Base64 包):

byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM