如何在Java中将字节数组转换为String?
问题描述:
如何在不转换的情况下将 bytes
数组转换为 String
?
How can I convert a array of bytes
to String
without conversion?.
我试过:
String doc=new String( bytes);
但doc文件与字节不同(字节是二进制信息)。例如:
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
和 bytes2
是不同的。
PS:UTF-8不起作用,因为它转换了不同值的某些字节。我测试过它不起作用。
PS: UTF-8 Does not work because it convert some bytes in different values. I tested and it does not work.
PS2:不,我不想要 BASE64
。
PS2: And no, I don't want BASE64
.
答
您需要指定所需的编码,例如对于UTF-8
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
和 doc2
将是相同的。
要解码 byte []
,你需要知道使用了什么编码来确保它能正确解码。
To decode a byte[]
you need to know what encoding was used to be sure it will decode correctly.