600

Is there any way to convert Java String to a byte[] (not the boxed 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 I'm getting separate 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 a byte[] 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());
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Mkl Rjv
  • 6,815
  • 5
  • 29
  • 47
  • 2
    http://stackoverflow.com/questions/5499924/convert-java-string-to-byte-array – Paddyd Sep 02 '13 at 10:41
  • 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 02 '13 at 10:54
  • 13
    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 02 '13 at 20:32

8 Answers8

1054

The object your method decompressGZIP() needs is a byte[].

So the basic, technical answer to the question you have asked is:

byte[] b = string.getBytes();
byte[] b = string.getBytes(Charset.forName("UTF-8"));
byte[] b = string.getBytes(StandardCharsets.UTF_8); // Java 7+ only

However the problem you appear to be wrestling with is that this doesn't display very well. Calling toString() will just give you the default Object.toString() which is the class name + memory address. In your result [B@38ee9f13, the [B means byte[] and 38ee9f13 is the memory address, separated by an @.

For display purposes you can use:

Arrays.toString(bytes);

But this will just display as a sequence of comma-separated integers, which may or may not be what you want.

To get a readable String back from a byte[], use:

String string = new String(byte[] bytes, Charset charset);

The reason the Charset version is favoured, is that all String objects in Java are stored internally as UTF-16. When converting to a byte[] you will get a different breakdown of bytes for the given glyphs of that String, depending upon the chosen charset.

Stewart
  • 17,616
  • 8
  • 52
  • 80
  • 28
    string.getBytes("UTF-8") requires handling an UnsupportedEncodingException, while string.getBytes(Charset.forName("UTF-8")) does not. Arguing as to which method is "better" I leave as an exercise for the reader. – Michael Warner Oct 22 '14 at 20:27
  • 20
    `string.getBytes(StandardCharsets.UTF_8)` can also be used, and it is the same as `string.getBytes(Charset.forName("UTF-8"))` – Bahadır Yağan Nov 15 '14 at 17:07
  • 3
    I believe `StandardCharsets` is new with Java 7 – Stewart Jan 04 '15 at 10:53
  • See http://stackoverflow.com/questions/6698354/where-to-get-utf-8-string-literal-in-java – Stewart Jan 04 '15 at 10:54
  • I have a problem I use getBytes to convert my string to bytes, but I cannot seems to get back the string from it. I tried .toString() – LoveMeow Oct 02 '15 at 16:51
  • Try the constructor `new String(byte[] bytes, Charset charset) ` – Stewart Oct 03 '15 at 17:40
  • 2
    I don't understand why this answer got so many upvotes. It may be right, but it's not very helpful ... just a couple of lines of code, most of which the OP already had, and not explaining what difference `Charset.forName("UTF-8")` makes or why it's important. – LarsH Oct 13 '15 at 20:43
  • 5
    @LarsH You make a good point. To be honest, I never expected this answer to become so popular. I have now expanded the answer in order to "deserve" the upvotes. Hopefully it's an improvement. – Stewart Oct 14 '15 at 11:13
  • In my case it was getBytes("ISO-8859-1"); For ISO Latin Alphabet. Thanks for the answer. This Direct me to the correct path. – Dinith Rukshan Kumara Oct 03 '21 at 12:53
  • @DinithRukshanKumara It's worth looking at this https://stackoverflow.com/questions/10643694/iso-8859-1-true-false – Stewart Oct 04 '21 at 08:52
65
  String example = "Convert Java String";
  byte[] bytes = example.getBytes();
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
  • 13
    Beware: [getBytes()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#getBytes()) is platform dependent. Better choice is to use [getBytes(StandardCharsets.UTF_8)](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#getBytes(java.nio.charset.Charset)) – Anand Rockzz Jan 22 '17 at 21:11
  • 1
    Method getBytes is deprecated now. – D.A.H Oct 12 '22 at 10:57
17

Simply:

String abc="abcdefghight";

byte[] b = abc.getBytes();
eebbesen
  • 5,070
  • 8
  • 48
  • 70
Bhavesh
  • 889
  • 1
  • 10
  • 16
  • What if `abc` contains non US-ASCII characters, like `"greater than 2³² − 1"` or just binary data (like "�A���b2")? – U. Windl Jul 25 '18 at 13:03
  • this does not work for characters like `� ` this string has only 5 characters. However when I use `getBytes()` i got 7 characters. – Teocci Jan 04 '19 at 05:53
  • Method getBytes is deprecated now. – D.A.H Oct 12 '22 at 10:56
15

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

String data = "sample data";
byte[] byteData = data.getBytes();
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
11

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

Vimal Bera
  • 10,346
  • 4
  • 25
  • 47
8

You might wanna try return new String(byteout.toByteArray(Charset.forName("UTF-8")))

Lucas Hoepner
  • 1,437
  • 1
  • 16
  • 21
0

I know I'm a little late tothe party but thisworks pretty neat (our professor gave it to us)

public static byte[] asBytes (String s) {                   
           String tmp;
           byte[] b = new byte[s.length() / 2];
           int i;
           for (i = 0; i < s.length() / 2; i++) {
             tmp = s.substring(i * 2, i * 2 + 2);
             b[i] = (byte)(Integer.parseInt(tmp, 16) & 0xff);
           }
           return b;                                            //return bytes
    }
  • 2
    This decodes hex-encoded byte array. Something very different from what this question is about. – Palec May 12 '18 at 14:10
-1

It is not necessary to change java as a String parameter. You have to change the c code to receive a String without a pointer and in its code:

Bool DmgrGetVersion (String szVersion);

Char NewszVersion [200];
Strcpy (NewszVersion, szVersion.t_str ());
.t_str () applies to builder c ++ 2010
Yardack
  • 7
  • 1