java - Java 中的 Base64 字符串转 byte[]

标签 java string base64 byte encoder-decoder

<分区>

我正在尝试将 base64 字符串转换为字节数组,但它抛出以下错误

java.lang.IllegalArgumentException: Illegal base64 character 3a

我尝试了以下选项 userimage is base64 string

byte[] img1 = org.apache.commons.codec.binary.Base64.decodeBase64(userimage);`

/* byte[] decodedString = Base64.getDecoder().decode(encodedString.getBytes(UTF_8));*/
/* byte[] byteimage =Base64.getDecoder().decode( userimage );*/
/* byte[] byteimage =  Base64.getMimeDecoder().decode(userimage);*/`

最佳答案

您可以使用java.util.Base64 包将字符串解码为byte[]。 下面是我用于编码和解码的代码。

对于 Java 8:

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class Example {

    public static void main(String[] args) {
        try {
            byte[] name = Base64.getEncoder().encode("hello World".getBytes());
            byte[] decodedString = Base64.getDecoder().decode(new String(name).getBytes("UTF-8"));
            System.out.println(new String(decodedString));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

对于 Java 6:

import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;

public class Main {

    public static void main(String[] args) {
        try {
            byte[] name = Base64.encodeBase64("hello World".getBytes());
            byte[] decodedString = Base64.decodeBase64(new String(name).getBytes("UTF-8"));
            System.out.println(new String(decodedString));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

关于java - Java 中的 Base64 字符串转 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41935207/

相关文章:

java - 如何将进度对话框与 Android 中的服务相关联

java - 应用服务器启动时间比较?

php - 如何解码此图像数据以在 HTML 中显示

java - BQ 加载具有不同模式的 Avro 文件,仅添加字段

java - 正确调用不同类中的方法 | java

c - 为什么要为该数组中的第一个元素打印垃圾?

swift - tiffRepresentation 和 bitmapRepresentation 在 Base64 字符串编码方面的区别?

c# - 在 ASP.Net/C# 中验证 Base64 图像

java - String 类在 Java 内部是如何工作的?

java - 如何切换字符串中的字母