To convert a Java String
to a byte
array, you can use the getBytes
method of the String
class. This method returns a byte
array that represents the string using the default platform encoding.
Here's an example of how to use the getBytes
method:
String s = "hello"; byte[] bytes = s.getBytes();
You can also specify a specific encoding to use when converting the string to a byte
array. For example, to use the UTF-8
encoding, you can use the following code:
String s = "hello"; byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
It's important to use the same encoding when converting a byte
array back to a String
as when converting the String
to a byte
array, to ensure that the resulting String
is the same as the original.
Here's an example of how you can convert a byte
array back to a String
using the UTF-8
encoding:
byte[] bytes = {'h', 'e', 'l', 'l', 'o'}; String s = new String(bytes, StandardCharsets.UTF_8);
You can find more information about character encodings and the getBytes
and String
constructors in the Java documentation.