javax.xml.bind中的Base64编码的连接codeR /德codeR吃串的最后两个字符 [英] javax.xml.bind's Base64 encoder/decoder eats last two characters of string

查看:156
本文介绍了javax.xml.bind中的Base64编码的连接codeR /德codeR吃串的最后两个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Base64编码一些字符串转换,并很高兴地看到,我没有推出自己的转炉 - Java提供了一个用 javax.xml.bind.DataConverter 。然而,它存在一些问题。下面是我的时间与一个Jython REPL输出:

 >>>进口javax.xml.bind.DatatypeConverter直流
>>>进口java.lang.String中为String
>>>高清美孚(文本):
...返回DC.printBase64Binary(DC.parseBase64Binary(字符串(文本)))
...
>>>富(你好)
'地狱'
>>>富(这,这是一个句子打断。)
Thisitsapunctuatedsenten
>>>富(\\富\\\\栏\\)
foob
>>>富(\\富\\\\栏\\12)
foobar12
>>>富(\\富\\\\栏\\1)
foob

正如你所看到的,它不能处理非字母数字字符在所有,也经常 - 但并不总是 - 由两个字符截断字符串<​​/ P>

我想这可能是时间只写我自己的类,但我现在困扰,要么一)我没有在阅读的javadoc或东西二)如预期类不起作用。

因此​​,任何帮助是非常AP preciated;先谢谢了。


解决方案

你好不是一个base64字符串,所以解析失败。您必须将字符串转换成字节数组(试行字符串(文本).getBytes(UTF-8')),然后调用 DC.printBase64Binary ()字节数组来获得Base64编码数据上。

DC.parseBase64Binary()开始转换这一带的Base64 codeD数据回字节数组(您可以再转换回字符串)。

I need to convert some strings using Base64 encoding, and was delighted to see that I didn't have to roll my own converter--Java provides one with javax.xml.bind.DataConverter. However, it has some problems. Here's the output of my time with a Jython REPL:

>>> import javax.xml.bind.DatatypeConverter as DC
>>> import java.lang.String as String
>>> def foo(text):
...   return DC.printBase64Binary(DC.parseBase64Binary(String(text)))
... 
>>> foo("hello")
'hell'
>>> foo("This, it's a punctuated sentence.")
'Thisitsapunctuatedsenten'
>>> foo("\"foo\" \"bar\"")
'foob'
>>> foo("\"foo\" \"bar\"12")
'foobar12'
>>> foo("\"foo\" \"bar\"1")
'foob'

As you can see, it doesn't handle non-alphanumeric characters at all, and also frequently--but not always--truncates the string by two characters.

I guess it might be time to just write my own class, but now I'm bothered that either a) I'm failing at reading the javadoc or something b) The class doesn't work as expected.

So any help is much appreciated; thanks in advance.

解决方案

hello is not a base64 String, so the parsing fails. You must convert the string into a byte array (try String(text).getBytes('UTF-8')) and then call DC.printBase64Binary() on the byte array to get the data in Base64.

DC.parseBase64Binary() will then convert this Base64 encoded data back into the byte array (which you can then convert back into a string).

这篇关于javax.xml.bind中的Base64编码的连接codeR /德codeR吃串的最后两个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆