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

查看:33
本文介绍了将 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);

<小时>

当我只发送 byte[] 而没有任何转换但当我将它从 byte[] 转换为 String 时,我的代理工作正常> 然后回到 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.

有人可以帮忙吗?=]

推荐答案

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> 标题

如果没有办法找出编码你是随机垃圾,而不是文本数据.

If there is no way to find out the encoding you have random garbage, not text data.

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

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