仅使用JDK6进行Base64解码

kos*_*tja 22 java base64

关于JDK 5的这个问题说,JDK 5没有提供实现,但是JDK 6应该有一个sun.misc.Base64Decoder.

据我所知,这个类没有提供JDK,我也找不到任何其他类似的类.

那么,JDK6的情况怎么样?

我知道有许多实现,如Commons和JBoss,但我们有一个限制性的第三方lib策略,所以我试图避免重新发明轮子.

bes*_*sss 55

sun.miscJava中有官方(非)实现,但并不是人们想象的那样.

java.util.prefs.AbstractPreferences是有必要的方法来做到这一点.你必须覆盖put方法.

还有一个更容易使用:

javax.xml.bind.DatatypeConverter 它有两种感兴趣的方法:


澄清AbstractPreferences的base64性质:java.util.prefs.Preferences

    /**
     * Associates a string representing the specified byte array with the
     * specified key in this preference node.  The associated string is
     * the Base64 encoding of the byte array, as defined in RFC 2045, Section 6.8,
     * with one minor change: the string will consist solely of characters
     * from the Base64 Alphabet; it will not contain any newline
     * characters.  Note that the maximum length of the byte array is limited
     * to three quarters of MAX_VALUE_LENGTH so that the length
     * of the Base64 encoded String does not exceed MAX_VALUE_LENGTH.
     * This method is intended for use in conjunction with
     * {@link #getByteArray}.
     */
    public abstract void putByteArray(String key, byte[] value);

  • "DatatypeConverter"看起来很棒,但是! (3认同)

Joa*_*uer 10

不,Java 5和Java 6之间的情况没有变化.

遗憾的是,Java SE平台中没有正式的Base64实现.@bestsss表明,有实际上在Java SE 6(以及隐藏)执行Base64编码(见他的更详细的答案).

Sun JDK随附此类(sun.misc.Base64Decoder),但未指定且不应使用(特别是因为它不需要存在于其他实现甚至版本中).

如果您绝对需要避免使用第三方库(Apache Commons Codec将是Base64实现的传统提供程序),那么您可能希望将BSD(或类似的)许可版本复制到项目中.有一个公共域实现,就许可而言,它就像它获得的一样轻松.

  • Java没有在合理的位置提供内置的Base64编码器/解码器*,这完全是荒谬的. (4认同)
  • 有一个正式的impl.实际上有两个. (2认同)

Mar*_*rco 7

就像Joachim Sauer在先前的评论中所说的那样,JDK1.6已经捆绑了它自己的Base64实现(sun.misc。*),下面是一个示例:

String toEncode = "Encoding and Decoding in Base64 Test";
//Encoding in b64
String encoded = new BASE64Encoder().encode(toEncode.getBytes());
System.out.println(encoded);
//Decoding in b64
byte[] decodeResult = new BASE64Decoder().decodeBuffer(encoded);
System.out.println(new String(decodeResult));
Run Code Online (Sandbox Code Playgroud)

  • 不建议使用`sun`软件包(http://www.oracle.com/technetwork/java/faq-sun-packages-142232.html) (2认同)