getBytes
is a static method of the StringUtils
class that is used to convert the given string to a byte array for a given character set in a null-safe manner.
getBytes()
method of the String
class.StringUtils
StringUtils
is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the StringUtils
class as follows.
import org.apache.commons.lang3.StringUtils;
public static byte[] getBytes(String string, Charset charset)
String string
: string to convert to bytes.Charset charset
: Character set to encode the string with.The method returns an empty byte array if the passed string is null
. Otherwise the method returns the output of String.getBytes(Charset)
.
import org.apache.commons.lang3.StringUtils;import java.nio.charset.StandardCharsets;import java.util.Arrays;public class Main {public static void main(String[] args) {String s = "educative";System.out.println("Byte array for the string 'educative' is - " + Arrays.toString(StringUtils.getBytes(s, StandardCharsets.UTF_8)));System.out.println("Byte array for a null string is - " + Arrays.toString(StringUtils.getBytes(null, StandardCharsets.UTF_8)));}}
Byte array for the string 'educative' is - [101, 100, 117, 99, 97, 116, 105, 118, 101]
Byte array for a null string is - []
educative
stringThe output of the method when the string above is passed is [101, 100, 117, 99, 97, 116, 105, 118, 101]
. The byte array is returned as the string is not null.
null
stringThe output of the method when the string above is passed is []
. An empty byte array is returned as the string is null
.