How to convert String to byte[] in Java?
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);
Table of contents
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.mkyong.string;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class ConvertStringToBytes {
public static void main(String[] args) {
String example = "This is an example";
// the best , java 1.7+
byte[] output = example.getBytes(StandardCharsets.UTF_8);
System.out.println("Text : " + example);
String base64encoded = Base64.getEncoder().encodeToString(output);
System.out.println("Text [Base64] : " + base64encoded);
}
}
Output
Terminal
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.mkyong.string;
import java.nio.charset.StandardCharsets;
public class ConvertBytesToString {
public static void main(String[] args) {
// String to byte[]
byte[] bytes = "mkyong".getBytes(StandardCharsets.UTF_8);
// byte[] to String
String s = new String(bytes, StandardCharsets.UTF_8);
// mkyong
System.out.println(s);
}
}
Output
Terminal
mkyong
3. Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-string
thx! helped me
Thank you, it saves a lot of time.