将byte []转换为String然后再转换为byte [] [英] Conversion of byte[] into a String and then back to a byte[]

查看:89
本文介绍了将byte []转换为String然后再转换为byte []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理代理服务器。我在 byte [] 中获取数据,我将其转换为 String 来执行某些操作。现在当我将这个新的 String 转换回 byte [] 时,它会导致未知问题。

I am working on a proxy server. I am getting data in byte[] which I convert into a String to perform certain operations. Now when i convert this new String back into a byte[] it causes unknown problems.

所以主要是因为我需要知道如何正确地将 byte [] 转换为 String 然后再回到 byte []

So mainly its like I need to know how to correctly convert abyte[] into a String and then back into a byte[] again.

我试图转换 byte [] String 然后再回到 byte [] (以确保它不是我的操作导致问题)。

I tried to just convert the byte[] to String and then back to byte[] again (to make sure thats its not my operations that are causing problems).

所以它就像:

// where reply is a byte[]

String str= new String(reply,0, bytesRead);
streamToClient.write(str.getBytes(), 0, bytesRead);

不等于

streamToClient.write(reply, 0, bytesRead);






当我发送<我的代理工作正常code> byte [] 没有任何转换,但当我将它从 byte [] 转换为 String <时/ code>然后回到 byte [] 它会导致问题。


my proxy works fine when I just send the byte[] without any conversion but when I convert it from byte[] to a String and then back to a byte[] its causes problems.

可以请一些人请救命? =]

Can some one please help? =]

推荐答案

byte [] 转换为的最佳方法 String 并返回 byte [] 根本不会这样做。

The best way to convert a byte[] to String and back into a byte[] is not to do it at all.

如果必须,您必须知道用于生成 byte [] 的编码,否则操作使用平台默认编码,这可能会破坏数据,因为并非所有编码都可以编码所有可能的字符串,并且并非所有可能的字节序列在所有编码中都是合法的。这就是你的情况。

If you have to, you must know the encoding that was used to produce the byte[], otherwise the operation uses the platform default encoding, which can corrupt the data because not all encodings can encode all possible strings, and not all possible byte sequences are legal in all encodings. This is what's happening in your case.

至于如何找出编码,取决于:

As for how to find out the encoding, that depends:


  • 如果您使用的是HTTP,请查看 Content-Type标题

  • 如果您的数据是XML,您应该使用XML解析器,它将为您处理编码

  • 如果您的数据是HTML页面,可能还有 < meta http-equiv> header

  • If you're using HTTP, look at the Content-Type header
  • If your data is XML, you should be using an XML parser, which will handle the encoding for you
  • If your data is HTML pages, there might also be a <meta http-equiv> header

如果无法找到编码,则随机垃圾,而不是文本数据

这篇关于将byte []转换为String然后再转换为byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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