java中将base64字符串转换为byte[] [英] Base64 String to byte[] in java

查看:78
本文介绍了java中将base64字符串转换为byte[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Base64字符串转换为字节数组,但引发以下错误

java.lang.IllegalArgumentException:非法的base64字符3a

我尝试了以下选项:userimage is base64字符串

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中将base64字符串转换为byte[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆