0

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!

Amin Sh
  • 2,684
  • 2
  • 27
  • 42

4 Answers4

2

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thanks. I wanna send an array of byte(result of a compressed String) in JMS properties, but it's not possible. Solution maybe was to cast it to string representation of those bytes. – Amin Sh Dec 12 '13 at 13:08
1

do like this

byte[] bytes = str.getBytes()

if you consider characters encoding then do like this

byte[] bytes = str.getBytes("UTF-8");
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
1

How can I convert str content to byte[] ?

byte[] bites = str.getBytes(Charset.forName("UTF-8"));
devnull
  • 118,548
  • 33
  • 236
  • 227
-1

try this way

byte[] b=str.getBytes();

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();
    }
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
  • downvoter my answer was as per the http://stackoverflow.com/revisions/d6847d8c-991d-4c01-82be-a3a0e2c6d25e/view-source but OP modified the question.Now I have also modified the answer – SpringLearner Dec 13 '13 at 04:15