用Java解码Base64字符串

时间:2023-02-07 18:34:48

I'm trying to decode a simple Base64 string, but am unable to do so. I'm currently using the org.apache.commons.codec.binary.Base64 package.

我正在尝试解码一个简单的Base64字符串,但我无法这样做。我目前正在使用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.

上面的代码不会抛出错误,而是不会按预期输出解码后的字符串。

3 个解决方案

#1


52  

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");

#2


2  

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));

#3


1  

Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):

通常base64用于图像。如果你想解码一个图像(在这个例子中使用org.apache.commons.codec.binary.Base64包进行jpg):

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

#1


52  

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");

#2


2  

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));

#3


1  

Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):

通常base64用于图像。如果你想解码一个图像(在这个例子中使用org.apache.commons.codec.binary.Base64包进行jpg):

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