Reputation: 2814
Here is my code:
byte[] bytes = ZipUtil.compress("string");
String str = bytes.toString();
//----------
System.out.println("bytes: " + bytes);
System.out.println("str: " + str);
System.out.println("str.getBytes(): " + str.getBytes());
As you see ZipUtil.compress()
returns byte[]
.
How can I convert str
content to byte[] ?
UPDATE:
output:
bytes: [B@6fd33eef
str: [B@6fd33eef
str.getBytes(): [B@15c8f644
As you see, if I use str.getBytes()
the content will be changed!
Upvotes: 0
Views: 510
Reputation: 13854
try this way
byte[] b=str.getBytes();
Update as per your modified question,do this way
byte[] b = str.getBytes("UTF-8");
But if you do this way then compiler will complain to add you throws declaration or surround with try-catch block So the code will be like this
try {
byte[] b=str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Upvotes: -1
Reputation: 692231
First of all, calling toString()
on an array won't return a String containing the bytes in the array. It will return the type of the array ([B
means array of bytes) followed by its hashCode: [B@6fd33eef
. So your code isn't correct.
You might use new String(bytes)
to create a String from the byte array content, but that would also be incorrect, because it would depend on your default encoding, and the bytes might not represent valid characters in this encoding. Only iso8859-1 would work, but you would get a String full of non-printable characters.
You probably want a printable string, and not garbage characters in your String, so you need a Base64 or Hex encoder to transform the bytes into a String and vice-versa. Guava has such an encoder, as well as Apache commons-codec. Both provide methods to encode a byte array into a printable Base64 String, and to decode this Base64 string into the original byte array.
Upvotes: 2
Reputation: 26084
do like this
byte[] bytes = str.getBytes()
if you consider characters encoding then do like this
byte[] bytes = str.getBytes("UTF-8");
Upvotes: 1
Reputation: 123678
How can I convert str content to byte[] ?
byte[] bites = str.getBytes(Charset.forName("UTF-8"));
Upvotes: 1