How to convert array of byte to String in Java? [d

2020-05-26 08:57发布

How can I convert a array of bytes to String without conversion?.

I tried:

  String doc=new String( bytes);

But the doc file is not the same than the bytes (the bytes are binary information). For example:

  String doc=new String( bytes);
  byte[] bytes2=doc.getBytes();

bytes and bytes2 are different.

PS: UTF-8 Does not work because it convert some bytes in different values. I tested and it does not work.

PS2: And no, I don't want BASE64.

3条回答
兄弟一词,经得起流年.
2楼-- · 2020-05-26 09:18

You need to specify the encoding you want e.g. for UTF-8

String doc = ....
byte[] bytes = doc.getBytes("UTF-8");
String doc2 = new String(bytes, "UTF-8");

doc and doc2 will be the same.

To decode a byte[] you need to know what encoding was used to be sure it will decode correctly.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-05-26 09:38

The "proper conversion" between byte[] and String is to explicitly state the encoding you want to use. If you start with a byte[] and it does not in fact contain text data, there is no "proper conversion". Strings are for text, byte[] is for binary data, and the only really sensible thing to do is to avoid converting between them unless you absolutely have to.

If you really must use a String to hold binary data then the safest way is to use Base64 encoding.

Source by Michael Borgwardt

查看更多
一夜七次
4楼-- · 2020-05-26 09:43

Here's one way to convert an array of bytes into a String and back:

String doc=new String(bytes, "ISO-8859-1");
byte[] bytes2=doc.getBytes("ISO-8859-1");

A String is a sequence of characters, so you'll have to somehow encode bytes as characters. The ISO-8859-1 encoding maps a single, unique character for each byte, so it's safe to use it for the conversion. Note that other encodings, such as UTF-8, are not safe in this sense because there are sequences of bytes that don't map to valid strings in those encodings.

查看更多
登录 后发表回答