Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is there any way to convert Java String to byte[] array?

Note: Its byte[] array and not the wrapper Byte[].

In trying this:

System.out.println(response.split("\r\n\r\n")[1]);
System.out.println("******");
System.out.println(response.split("\r\n\r\n")[1].getBytes().toString());

And Im getting seperate outputs. Unable to display 1st output as it is a gzip string.

<A Gzip String>
******
[B@38ee9f13

The second is an address. Is there anything I'm doing wrong? I need the result in byte[] array to feed it to gzip decompressor, which is as follows.

String decompressGZIP(byte[] gzip) throws IOException {
    java.util.zip.Inflater inf = new java.util.zip.Inflater();
    java.io.ByteArrayInputStream bytein = new java.io.ByteArrayInputStream(gzip);
    java.util.zip.GZIPInputStream gzin = new java.util.zip.GZIPInputStream(bytein);
    java.io.ByteArrayOutputStream byteout = new java.io.ByteArrayOutputStream();
    int res = 0;
    byte buf[] = new byte[1024];
    while (res >= 0) {
        res = gzin.read(buf, 0, buf.length);
        if (res > 0) {
            byteout.write(buf, 0, res);
        }
    }
    byte uncompressed[] = byteout.toByteArray();
    return (uncompressed.toString());
}
share|improve this question
2  
 
Sorry, I'm trying to convert a String to bytearray and back and getting a wrong result. I'll edit it in a while and get back. –  Mkl Rjv Sep 2 at 10:54
2  
Your problem is that String.getBytes() does indeed return a byte array, but your belief that the toString() of a byte array will return a useful result is incorrect. –  Louis Wasserman Sep 2 at 20:32

6 Answers

It's simply

byte[] byteArray = yourString.getBytes();

You can see javadoc

share|improve this answer
  String example = "Convert Java String";
  byte[] bytes = example.getBytes();
share|improve this answer
byte[] b = string.getBytes();
byte[] b = string.getBytes(Charset.forName("UTF-8"));
share|improve this answer

You can use String.getBytes() which returns the byte[] array.

share|improve this answer

Try using String.getBytes(). It returns a byte[] representing string data. Example:

String data = "sample data";
byte[] byteData = data.getBytes();
share|improve this answer

simply do it by

String abc="abcdefghight";

byte[] b = abc.getBytes();

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.