Java Program to Convert Byte Array to String
Last Updated :
03 May, 2022
A byte is 8 bits of binary data so do byte array is an array of bytes used to store the collection of binary data. There are multiple ways to change byte array to String in Java, you can either use methods from JDK, or you can use open-source complementary APIs like Apache commons and Google Guava. These APIs provide at least two sets of methods to create a String from a byte array; one, which uses default platform encoding, and the other which takes character encoding.
Different Methods to Convert Byte Array to String
- Using UTF-8 encoding
- Using String Class Constructor
Method 1: Using UTF-8 encoding
It's also one of the best practices for specifying character encoding while converting bytes to the character in any programming language. It might be possible that your byte array contains non-printable ASCII characters. Let's first see JDK's way of converting byte[] to a string. Some programmers, also recommend using Charset over String for specifying character encoding, e.g. instead of “UTF-8” use StandardCharsets.UTF_8 mainly to avoid Unsupported Encoding Exception in the worst case.
Case 1: Without character encoding
We can convert the byte array to String for the ASCII character set without even specifying the character encoding. The idea is to pass the byte[] to the string. It is as shown in the below example which is as follows:
Example:
Java
// Java Program to Convert Byte Array to String
// Without character encoding
// Importing required classes
import java.io.IOException;
import java.util.Arrays;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
throws IOException
{
// Getting bytes from the custom input string
// using getBytes() method and
// storing it in a byte array
byte[] bytes = "Geeksforgeeks".getBytes();
System.out.println(Arrays.toString(bytes));
// Creating a string from the byte array
// without specifying character encoding
String string = new String(bytes);
// Printing the string
System.out.println(string);
}
}
Output[71, 101, 101, 107, 115, 102, 111, 114, 103, 101, 101, 107, 115]
Geeksforgeeks
Case 2: With character encoding
We know that a byte holds 8 bits, which can have up to 256 distinct values. This works fine for the ASCII character set, where only the first 7 bits are used. For character sets with more than 256 values, we should explicitly specify the encoding, which tells how to encode characters into sequences of bytes.
Note: Here we are using StandardCharsets.UTF_8 to specify the encoding. Before Java 7, we can use the Charset. for Name("UTF-8").
Example 2:
Java
// Java Program to Convert Byte Array to String
// With character encoding
// Importing required classes
import java.io.IOException;
import java.nio.charset.StandardCharsets;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
throws IOException
{
// Custom input string is converted into array of
// bytes and stored
byte[] bytes = "Geeksforgeeks".getBytes(
StandardCharsets.UTF_8);
// Creating a string from the byte array with
// "UTF-8" encoding
String string
= new String(bytes, StandardCharsets.UTF_8);
// Print and display the string
System.out.println(string);
}
}
Method 2: Using String Class Constructor
Java
// Java Program to Illustrate Conversion of
// Byte Array to String
// Using String Class Constructor
// Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try {
// Getting bytes of input byte array
// using getBytes() method
byte[] input = "GeeksforGeeks".getBytes();
// Creating a corresponding string
String str = new String(input);
// Printing the above string
System.out.println(str);
}
// Catch block to handle exceptions
catch (Exception e) {
// Display exceptions along with line number
// using printStackTrace() method
e.printStackTrace();
}
}
}
Conclusion: We should focus on the type of input data when working with conversion between byte[] array and String in Java.
- Use String class when you input data is string or text content.
- Use Base64 class when you input data in a byte array.
Similar Reads
Java Program to Convert Byte Array to Hex String Byte Array - A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte array is 0. Hex String - A Hex String is a combination of the digits 0-9 and characters A-F, just like how a binary string comprises only 0's and 1's. Eg: "245FC" is a hexadec
5 min read
Java Program to Convert Hex String to Byte Array Hex String - A Hex String is a combination of the digits 0-9 and characters A-F, just like how a binary string comprises only 0's and 1's. Eg: "245FC" is a hexadecimal string. Byte Array - A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte
4 min read
Java Program to Convert Byte Array to Long A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte array is 0. Given an array of bytes, convert it to a long value. Example: Byte Array: 1 2 3 4 Long Value: 16909060 Equivalent Hexadecimal String: 0x1020304 There are numerous approaches fo
3 min read
Java Program to Convert Byte Array to Image A byte array is the array of bytes that is used to store the collection of binary data. For example, the byte array of an image stores the information of every pixel of the image. In the byte array, we can store the content of any file in binary format. We can initialize the byte array with the byte
3 min read
Java Program to Convert File to a Byte Array Here, we will go through the different ways to convert file to byte array in Java. Note: Keep a check that prior doing anything first. Create a file on the system repository to deal with our program\writing a program as we will be accessing the same directory through our programs. Methods: Using rea
3 min read
Java Program to Convert Byte Array to Object Converting byte array into Object and Object into a byte array process is known as deserializing and serializing. The class object which gets serialized/deserialized must implement the interface Serializable. Serializable is a marker interface that comes under package 'java.io.Serializable'.Byte Arr
2 min read
Java Program to Convert String to Byte Array Using getBytes() Method In Java, strings are objects that are backed internally by a char array. So to convert a string to a byte array, we need a getByte() method. It is the easiest way to convert a string to a byte array. This method converts the given string to a sequence of bytes using the platform's default charset an
2 min read
Java Program to Convert Char to Byte Given a char in Java, the task is to write a Java program that converts this char into Byte. Examples: Input: ch = 'A' Output: 65 Input: ch = 'B' Output 66 In Java, char is a primitive data type and it is used to declare characters. It has the capability to hold 16-bit unsigned Unicode characters. T
3 min read
How to Convert JSON Array to String Array in Java? JSON stands for JavaScript Object Notation. It is one of the widely used formats to exchange data by web applications. JSON arrays are almost the same as arrays in JavaScript. They can be understood as a collection of data (strings, numbers, booleans) in an indexed manner. Given a JSON array, we wil
3 min read
Java Program to Convert String to InputStream Given a string, the task is to convert the string to InputStream which is shown in the below illustrations. Illustration: Input : String : "Geeks for Geeks" Output : Input Stream : Geeks for Geeks Input : String : "A computer science portal" Output : Input stream : A computer science portal In order
2 min read