【问题标题】:work sun.misc.BASE64Encoder/Decoder for getting byte[]工作 sun.misc.BASE64Encoder/Decoder 以获取字节 []
【发布时间】:2012-03-07 20:42:06
【问题描述】:

我正在尝试使用 sun.misc.BASE64Encoder/Decoder,但是这段代码:

(new sun.misc BASE64Encoder()).encode(new    
    sun.misc.BASE64Decoder().decodeBuffer("test string XML:"))

返回“测试/字符串/XML/” 我很尴尬

【问题讨论】:

    标签: java


    【解决方案1】:

    不要使用sun.misccom.sun 类。不保证它们在不同版本的 jre 之间保持一致。

    使用commons-codecBase64.encodeBase64(..)Base64.decodeBase64(..)

    【讨论】:

    • 呵呵.. 我把我最近使用的 sun.misc.BASE64Encoder/Decoder 的项目发给了客户。不知道不同jre的不一致。我希望这是一个罕见的问题。
    • 自 JDK 1.1 以来它实际上一直运行良好,但使用内部 API 仍然很难看。从纯粹实用的角度来看,您无需担心。
    【解决方案2】:

    使用类:

    javax.xml.bind.DatatypeConverter
    

    它有 2 种有趣的方法:

    public static byte[] parseBase64Binary( String lexicalXSDBase64Binary )
    public static String printBase64Binary( byte[] val )
    

    【讨论】:

    • 我几天来一直在寻找一种可靠的方法来使用本机库转换 Base64。谢谢!
    【解决方案3】:

    您首先解码字符串“test string XML:”,它不是真正有效的 Base64,因为它包含空格和冒号,它们都不是有效的 B64 字符。我认为你的意思是先编码然后解码,像这样:

    (new sun.misc.BASE64Decoder().decodeBuffer(new sun.misc.BASE64Encoder().encode("test string XML:"))
    

    【讨论】:

      【解决方案4】:

      我想你想要:

      String s = "Hello world";
      new sun.misc.BASE64Encoder().encode(s.getBytes("UTF-8"));
      

      更好的是,按照前面的答案建议使用 commons utils。如果您不能在另一个 jar 上添加外部依赖,请仅使用 sun.misc.Base64Encoder。

      【讨论】:

        猜你喜欢
        • 2020-10-18
        • 1970-01-01
        • 2019-11-19
        • 1970-01-01
        • 2018-11-29
        • 2015-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多