如何将二进制数据转换为字符串并返回Java? [英] How do you convert binary data to Strings and back in Java?

查看:624
本文介绍了如何将二进制数据转换为字符串并返回Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文件中有二进制数据,我可以读入一个字节数组并且没有问题。现在,我需要通过网络连接将部分数据作为XML文档中的元素发送。我的问题是,当我将数据从字节数组转换为String并返回到字节数组时,数据就会被破坏。我已经在一台机器上对此进行了测试,以将问题与String转换隔离开来,所以我现在知道它没有被XML解析器或网络传输损坏。

I have binary data in a file that I can read into a byte array and process with no problem. Now I need to send parts of the data over a network connection as elements in an XML document. My problem is that when I convert the data from an array of bytes to a String and back to an array of bytes, the data is getting corrupted. I've tested this on one machine to isolate the problem to the String conversion, so I now know that it isn't getting corrupted by the XML parser or the network transport.

我现在所拥有的是

byte[] buffer = ...; // read from file
// a few lines that prove I can process the data successfully
String element = new String(buffer);
byte[] newBuffer = element.getBytes();
// a few lines that try to process newBuffer and fail because it is not the same data anymore

有没有人知道如何将二进制转换为String并返回而不会丢失数据?

Does anyone know how to convert binary to String and back without data loss?

回答:谢谢Sam。我觉得自己像个白痴。我昨天得到了回答,因为我的SAX解析器在抱怨。出于某些原因,当我遇到这个看似独立的问题时,我并没有想到这是同一问题的新症状。

Answered: Thanks Sam. I feel like an idiot. I had this answered yesterday because my SAX parser was complaining. For some reason when I ran into this seemingly separate issue, it didn't occur to me that it was a new symptom of the same problem.

编辑:仅供参考为了完整起见,我使用了 Base64 来自 Apache Commons 的课程 Codec 包来解决这个问题。

Just for the sake of completeness, I used the Base64 class from the Apache Commons Codec package to solve this problem.

推荐答案

如果你在base64中对它进行编码,这个将任何数据转换为ascii安全文本,但base64编码数据大于原始数据

If you encode it in base64, this will turn any data into ascii safe text, but base64 encoded data is larger than the orignal data

这篇关于如何将二进制数据转换为字符串并返回Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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