我有一个Base64编码的图像。Java中最好的解码方法是什么?希望只使用Sun Java 6中包含的库。


当前回答

给出一个javax.xml.bind.DatatypeConverter的测试编码/解码示例,使用方法parseBase64Binary()和printBase64Binary()引用@jeremy-ross和@nightfirecat answer。

@Test
public void EncodeDecode() {
    //ENCODE
    String hello = "Hello World";
    byte[] helloBytes = hello.getBytes(StandardCharsets.UTF_8);
    String encodedHello = DatatypeConverter.printBase64Binary(helloBytes);
    LOGGER.info(hello + " encoded=> " + encodedHello);

    //DECODE
    byte[] encodedHelloBytes = DatatypeConverter.parseBase64Binary(encodedHello);
    String helloAgain = new String(encodedHelloBytes, StandardCharsets.UTF_8) ;
    LOGGER.info(encodedHello + " decoded=> " + helloAgain);

    Assert.assertEquals(hello, helloAgain);
}

结果:

INFO - Hello World encoded=> SGVsbG8gV29ybGQ=
INFO - SGVsbG8gV29ybGQ= decoded=> Hello World

其他回答

我知道现在回答有点晚了,但对于JDK 8及以上版本。

Base64.getEncoder().encodeToString("anyStringData".getBytes());
Base64.getDecoder().decode("encodedData");

进口

import java.util.Base64;

请参考此OracleDocs !

番石榴现在内置了Base64解码。

使用BaseEncoding.base64 () .decode ()

至于处理输入使用中可能出现的空白

BaseEncoding.base64 () .decode (CharMatcher.WHITESPACE.removeFrom(…));

有关更多信息,请参阅此讨论

给出一个javax.xml.bind.DatatypeConverter的测试编码/解码示例,使用方法parseBase64Binary()和printBase64Binary()引用@jeremy-ross和@nightfirecat answer。

@Test
public void EncodeDecode() {
    //ENCODE
    String hello = "Hello World";
    byte[] helloBytes = hello.getBytes(StandardCharsets.UTF_8);
    String encodedHello = DatatypeConverter.printBase64Binary(helloBytes);
    LOGGER.info(hello + " encoded=> " + encodedHello);

    //DECODE
    byte[] encodedHelloBytes = DatatypeConverter.parseBase64Binary(encodedHello);
    String helloAgain = new String(encodedHelloBytes, StandardCharsets.UTF_8) ;
    LOGGER.info(encodedHello + " decoded=> " + helloAgain);

    Assert.assertEquals(hello, helloAgain);
}

结果:

INFO - Hello World encoded=> SGVsbG8gV29ybGQ=
INFO - SGVsbG8gV29ybGQ= decoded=> Hello World

特别是在通用Codec:类Base64解码(byte[]数组)或编码(byte[]数组)

从Java 8开始,就有了官方支持的用于Base64编码和解码的API。 随着时间的推移,这可能会成为默认的选择。

该API包括java.util类。Base64及其嵌套类。它支持三种不同的风格:基本的、URL安全的和MIME。

使用“基本”编码的示例代码:

import java.util.Base64;

byte[] bytes = "Hello, World!".getBytes("UTF-8");
String encoded = Base64.getEncoder().encodeToString(bytes);
byte[] decoded = Base64.getDecoder().decode(encoded);
String decodedStr = new String(decoded, StandardCharsets.UTF_8);

java.util的文档。Base64还包括一些配置编码器和解码器的方法,以及使用不同的类作为输入和输出(字节数组,字符串,ByteBuffers, java。io流)。