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


当前回答

另一个迟来的答案,但我的基准测试表明,Jetty的Base64编码器的实现非常快。不如MiGBase64快,但比iHarder Base64快。

import org.eclipse.jetty.util.B64Code;

final String decoded = B64Code.decode(encoded, "UTF-8");

我还做了一些基准测试:

      library     |    encode    |    decode   
------------------+--------------+-------------
 'MiGBase64'      |  10146001.00 |  6426446.00
 'Jetty B64Code'  |   8846191.00 |  3101361.75
 'iHarder Base64' |   3259590.50 |  2505280.00
 'Commons-Codec'  |    241318.04 |   255179.96

这些是每秒跑数,所以越高越好。

其他回答

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

使用BaseEncoding.base64 () .decode ()

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

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

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

这是一个迟来的回答,但是Joshua Bloch在java.util.prefs包下提交了他的Base64类(当他为Sun工作时,嗯,Oracle)。这个类从JDK 1.4开始就存在了。

E.g.

String currentString = "Hello World";
String base64String = java.util.prefs.Base64.byteArrayToBase64(currentString.getBytes("UTF-8"));

给出一个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

另一个迟来的答案,但我的基准测试表明,Jetty的Base64编码器的实现非常快。不如MiGBase64快,但比iHarder Base64快。

import org.eclipse.jetty.util.B64Code;

final String decoded = B64Code.decode(encoded, "UTF-8");

我还做了一些基准测试:

      library     |    encode    |    decode   
------------------+--------------+-------------
 'MiGBase64'      |  10146001.00 |  6426446.00
 'Jetty B64Code'  |   8846191.00 |  3101361.75
 'iHarder Base64' |   3259590.50 |  2505280.00
 'Commons-Codec'  |    241318.04 |   255179.96

这些是每秒跑数,所以越高越好。

你可以从编码的Base64字符串中写入或下载文件:

Base64 base64 = new Base64(); 
String encodedFile="JVBERi0xLjUKJeLjz9MKMSAwIG9iago8PCAKICAgL1R5cGUgL0NhdGFsb2cKICAgL1BhZ2VzIDIgMCBSCiAgIC9QYWdlTGF5b3V0IC9TaW5"; 
              byte[] dd=encodedFile.getBytes();
            byte[] bytes = Base64.decodeBase64(dd);

 response.setHeader("Content-disposition", "attachment; filename=\""+filename+"\"");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Expires", "-1");

            // actually send result bytes
            response.getOutputStream().write(bytes);

对我有用,希望对你也有用……