Java中的Base64字符串到字节[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41935207/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:48:01  来源:igfitidea点击:

Base64 String to byte[] in java

javastringbase64byteencoder-decoder

提问by Ninad Kulkarni

I am trying to convert base64 String to byte array but it is throwing following error

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

java.lang.IllegalArgumentException: Illegal base64 character 3a

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

I have tried following options userimage is base64 string

我试过以下选项 userimage 是 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);*/`

采纳答案by Ravi Koradia

You can use java.util.Base64package to decode the String to byte[]. Below code which I have used for encode and decode.

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

For Java 8 :

对于 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();
        }
    }

For Java 6 :

对于 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();
        }
    }
}