In Java, we can use str.getBytes(StandardCharsets.UTF_8) to convert a String into a byte[].
String str = "This is a String";
// default charset, a bit dangerous
byte[] output1 = str.getBytes();
// in old days, before java 1.7
byte[] output2 = str.getBytes(Charset.forName("UTF-8"));
// the best , java 1.7+ , new class StandardCharsets
byte[] output3 = str.getBytes(StandardCharsets.UTF_8);
1. Convert String to byte[]
Below is a complete example of converting a String to a byte[] type, and Base64 encodes it.
ConvertStringToBytes.java
package com.favtuts.string;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class ConvertStringToBytes {
public static void main(String[] args) {
String example = "This is an example";
// default charset, a bit dangerous
byte[] output1 = example.getBytes();
// in old days, before java 1.7
byte[] output2 = example.getBytes(Charset.forName("UTF-8"));
// the best , java 1.7+
byte[] output3 = example.getBytes(StandardCharsets.UTF_8);
System.out.println("Text : " + example);
// base64 encode
String base64encoded = Base64.getEncoder().encodeToString(output3);
System.out.println("Text [Base64] : " + base64encoded);
}
}
Output
Text : This is an example
Text [Base64] : VGhpcyBpcyBhbiBleGFtcGxl
2. Convert byte[] to String
In Java, we can use new String(bytes, StandardCharsets.UTF_8) to convert byte[] to a String.
ConvertBytesToString.java
package com.favtuts.string;
import java.nio.charset.StandardCharsets;
public class ConvertBytesToString {
public static void main(String[] args) {
// String to byte[]
byte[] bytes = "tuts.heomi.net".getBytes(StandardCharsets.UTF_8);
// byte[] to String
String s = new String(bytes, StandardCharsets.UTF_8);
// tuts.heomi.net
System.out.println(s);
}
}
Output
tuts.heomi.net
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-string