W3docs

Java Byte Array to String to Byte Array

To convert a byte array to a string and back to a byte array in Java, you can use the getBytes method of the String class and the getBytes method of the Charset class.

To convert a byte array to a string and back to a byte array in Java, you can use the getBytes method of the String class and the getBytes method of the Charset class.

Here is an example of how to convert a byte array to a string and back to a byte array:


import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

byte[] bytes = {0x48, 0x65, 0x6c, 0x6c, 0x6f};  // "Hello" in ASCII

// Convert byte array to string
String str = new String(bytes, StandardCharsets.US_ASCII);

// Convert string to byte array
byte[] bytes2 = str.getBytes(StandardCharsets.US_ASCII);

This will convert the byte array bytes to a string using the ASCII character set, and then convert the string back to a byte array using the same character set.

You can also use the Charset class to specify a different character set for the conversion:


import java.nio.charset.Charset;

byte[] bytes = {(byte)0x48, (byte)0x65, (byte)0x6c, (byte)0x6c, (byte)0x6f};  // "Hello" in ASCII
Charset utf8 = Charset.forName("UTF-8");

// Convert byte array to string
String str = new String(bytes, utf8);

// Convert string to byte array
byte[] bytes2 = str.getBytes(utf8);

This will convert the byte array bytes to a string using the specified charset, and then convert it back to a byte array using the same charset. Explicitly specifying a charset ensures platform-independent encoding behavior, avoiding issues with the system's default character set.