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 however mean that you have to handle the checked UnsupportedCharsetException
.
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);
Note that invalid characters and bytes may be replaced or skipped by these methods.
For more control - for instance for validating input - you're encouraged to use the CharsetEncoder
and CharsetDecoder
classes.