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

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

问题描述

我在一个文件中有二进制数据,我可以将其读入字节数组并毫无问题地进行处理.现在我需要通过网络连接将部分数据作为 XML 文档中的元素发送.我的问题是,当我将数据从字节数组转换为字符串并返回到字节数组时,数据已损坏.我已经在一台机器上对此进行了测试,以将问题与字符串转换隔离开来,所以我现在知道它没有被 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

有谁知道如何在不丢失数据的情况下将二进制转换为字符串并返回?

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

回答:谢谢山姆.我觉得自己像个白痴.我昨天回答了这个问题,因为我的 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天全站免登陆