In this post we'll see a Java program to convert a String to byte array and byte array to String in Java.
Converting String to byte[] in Java
String class has getBytes()
method which can be used to convert String to byte array in Java.
getBytes()- Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
There are two other variants of getBytes() method in order to provide an encoding for String.
- getBytes(Charset charset)
- getBytes(String charsetName)
import java.util.Arrays; public class StringToByte { public static void main(String[] args) { String str = "Example String"; byte[] b = str.getBytes(); System.out.println("Array " + b); System.out.println("Array as String" + Arrays.toString(b)); } }
Output
Array [B@2a139a55 Array as String[69, 120, 97, 109, 112, 108, 101, 32, 83, 116, 114, 105, 110, 103]
As you can see here printing the byte array gives the memory address so used Arrays.toString in order to print the array values.
Conversion of string to byte array with encoding
Suppose you want to use "UTF-8" encoding then it can be done in 3 ways.
String str = "Example String"; byte[] b; try { b = str.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } b = str.getBytes(Charset.forName("UTF-8")); b = str.getBytes(StandardCharsets.UTF_8);
Using str.getBytes("UTF-8") method to convert String to byte array will require to enclose it in a try-catch block as UnsupportedEncodingException is thrown.
To avoid that you can use str.getBytes(Charset.forName("UTF-8"))
method. Java 7 onward you can also use
str.getBytes(StandardCharsets.UTF_8);
Converting byte array to String in Java
String class has a constructor which takes byte array as an argument. Using that you can get the String from a byte array.
String(byte[] bytes)- Constructs a new String by decoding the specified array of bytes using the platform's default charset.
If you want to provide a specific encoding then you can use the following constructor-
String(byte[] bytes, Charset charset)- Constructs a new String by decoding the specified array of bytes using the specified charset.
public class StringToByte { public static void main(String[] args) { String str = "Example String"; // converting to byte array byte[] b = str.getBytes(); // Getting the string from a byte array String s = new String (b); System.out.println("String - " + s); } }
Output
String - Example String
That's all for this topic Convert String to Byte Array Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment