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
.
You need to specify the encoding you want e.g. for UTF-8
doc
anddoc2
will be the same.To decode a
byte[]
you need to know what encoding was used to be sure it will decode correctly.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
Here's one way to convert an array of bytes into a
String
and back:A
String
is a sequence of characters, so you'll have to somehow encode bytes as characters. TheISO-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 asUTF-8
, are not safe in this sense because there are sequences of bytes that don't map to valid strings in those encodings.