Conversion to and from bytes

suggest change

To encode a string into a byte array, you can simply use the String#getBytes() method, with one of the standard character sets available on any Java runtime:

byte[] bytes = "test".getBytes(StandardCharsets.UTF_8);

and to decode:

String testString = new String(bytes, StandardCharsets.UTF_8);

you can further simplify the call by using a static import:

import static java.nio.charset.StandardCharsets.UTF_8;
...
byte[] bytes = "test".getBytes(UTF_8);

For less common character sets you can indicate the character set with a string:

byte[] bytes = "test".getBytes("UTF-8");

and the reverse:

String testString = new String (bytes, "UTF-8");

This does mean that you have to handle the checked UnsupportedEncodingException. Charset.forName throws the unchecked UnsupportedCharsetException; String.getBytes(String) and new String(byte[], String) do not.


The following call will use the default character set. The default character set is platform specific and generally differs between Windows, Mac and Linux platforms.

byte[] bytes = "test".getBytes();

and the reverse:

String testString = new String(bytes);

By default these methods replace invalid characters and bytes. Skipping them requires a CharsetEncoder or CharsetDecoder configured to ignore errors. Those classes also give you a way to reject invalid input instead of replacing it.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents