$show=/label

How To Convert String To Byte Array and Vice Versa In Java 8

SHARE:

Learn how to convert String to Byte[] array in java and do it in reverse way byte array to String in java 8.

1. Overview

In this article, you will learn how to convert String to Byte[] array and vice versa in java programming.

First, let us explore the different ways using String.getBytes(), Charset.encode(), CharsetEncoder methods to convert String to a byte array, and last using java 8 Base64 api.

In the next section, you'll find similar methods for byte array to String.

How To Convert String To Byte Array and Vice Versa In Java 8


2. Java String To Byte[] Array

Basically,  String internally uses to store the Unicode characters in the array. We need to convert the characters into a sequence of bytes using a String.bytes() method. 

2.1. String.getBytes()

String API is already loaded with getBytes() methods that convert a string into bytes array.

You can anyone of the below methods.

public byte[] getBytes()
public byte[] getBytes(Charset charset)
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
 

String to byte array example:

package com.javaprogramto.arrays.bytearray;

public class StrintToByteArrayExample {

	public static void main(String[] args) {

		// creating string
		String string = "javaprogrmto.com";

		// string to byte array
		byte[] array1 = string.getBytes();

		// printing byte array
		for (int i = 0; i < array1.length; i++) {
			System.out.print(" " + array1[i]);
		}
	}
}
 

Output:

 106 97 118 97 112 114 111 103 114 109 116 111 46 99 111 109
 

It is good practice to use the other overloaded methods for getBytes().

getBytes() method uses the internally default character set using Charset.defaultCharset() and it is platform dependent.

You can pass the specific character set name to this method.

// creating string
String string = "javaprogrmto.com";
String characterSetName = "ASCII";

try {
	byte[] array2 = string.getBytes(characterSetName);

	// printing byte array
	for (int i = 0; i < array2.length; i++) {
		System.out.print(" " + array1[i]);
	}

} catch (UnsupportedEncodingException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
 

Output:

 106 97 118 97 112 114 111 103 114 109 116 111 46 99 111 109
 

UTF-8 conversion example:

		String str2 = "Welcome, JavaProgramto.com !!!!";
		Charset charset = StandardCharsets.UTF_8;
		byte[] array3 = str2.getBytes(charset);
		// printing byte array
		for (int j = 0; j < array3.length; j++) {
			System.out.print(" " + array3[j]);
		}

 

Output:

 87 101 108 99 111 109 101 44 32 74 97 118 97 80 114 111 103 114 97 109 116 111 46 99 111 109 32 33 33 33 33
 

UTF-16 conversion example:

	String str2 = "Welcome, JavaProgramto.com !!!!";
	Charset charset = StandardCharsets.UTF_16;
	byte[] array3 = str2.getBytes(charset);
	// printing byte array
	for (int j = 0; j < array3.length; j++) {
		System.out.print(" " + array3[j]);
	}
 

Output:

 -2 -1 0 87 0 101 0 108 0 99 0 111 0 109 0 101 0 44 0 32 0 74 0 97 0 118 0 97 0 80 0 114 0 111 0 103 0 114 0 97 0 109 0 116 0 111 0 46 0 99 0 111 0 109 0 32 0 33 0 33 0 33 0 33
  

2.2. Charset.encode() Method

Class Charset provides a method to encode the string using the encode() method and further convert it into bytes array using the array() method.

Look at the below program, input string has. different language characters and these. are not known by the ASCII charset and unknown characters will. be mapped to the default replacement of byte array.

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class CharsetEncode {

	public static void main(String[] args) {

		// creating string
		String inputStr = "javaprogrmto.com जावा";

		// create charset object
		Charset charset = StandardCharsets.US_ASCII;

		// encoding string
		ByteBuffer buffer = charset.encode(inputStr);

		// ByteBuffer to byte[] array
		byte[] array = buffer.array();

		// printing byte array
		for (int j = 0; j < array.length; j++) {
			System.out.print(" " + array[j]);
		}

	}
}
  

Output:

 106 97 118 97 112 114 111 103 114 109 116 111 46 99 111 109 32 63 63 63 63

2.3. CharsetEncoder.encode()

CharsetEncoder class works similarly to the above method but it provides the flexibility to work with the default unknown mappings using onUnmappableCharacter() and replaceWith() methods.

import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;

public class CharsetEncoderencode {

	public static void main(String[] args) throws CharacterCodingException {

		// creating string
		String inputStr = "javaprogrmto.com जावा";

		CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder();

		// Replacing the unmapping charset with zero's
		encoder.onMalformedInput(CodingErrorAction.IGNORE).onUnmappableCharacter(CodingErrorAction.REPLACE)
				.replaceWith(new byte[] { 0 });

		byte[] array = encoder.encode(CharBuffer.wrap(inputStr)).array();

		// printing byte array
		for (int j = 0; j < array.length; j++) {
			System.out.print(" " + array[j]);
		}

	}
}

  

Output:

 106 97 118 97 112 114 111 103 114 109 116 111 46 99 111 109 32 0 0 0 0
  

2.4 Java 8 Base64.getDecoder() 

In Java 8,  Base64 class is added with the getDecoder() method to get the decoder and call decode() method to covnert to byte[] array.

import java.nio.charset.CharacterCodingException;
import java.util.Base64;

public class Base64Decode {

	public static void main(String[] args) throws CharacterCodingException {

		// creating string
		String inputStr = "javaprogrmto.com जावा";

		// java 8 string to byte[]
		byte[] array = Base64.getDecoder().decode(inputStr);

		// printing byte array
		for (int j = 0; j < array.length; j++) {
			System.out.print(" " + array[j]);
		}

	}
}

  

3. Java Byte[] Array To String

Let us explore the different ways to do the conversion from byte[] array to String in java. This process is similar to the decoding.

Note: You should not use any character set to do decoding and should use the one which is used in encoding as string to a byte array. 

3.1 Using String Constructor

String constructor takes the byte array and converts into the string using the default charset.

public class StringConstructorDecode {

	public static void main(String[] args) {
		byte[] byteArray = { 106, 97, 118, 97, 112, 114, 111, 103, 114, 109, 116, 111, 46, 99, 111, 109 };

		String decode = new String(byteArray);

		System.out.println("Decoded string : " + decode);
	}
}
  

Output:

Decoded string : javaprogrmto.com

  

Passing the charset name to the String constructor. In the below example, we have passed the different charset which is used in. the encoding process.

 

	public static void main(String[] args) throws UnsupportedEncodingException {

		String charset = "IBM01140";
		byte[] byteArray = { 106, 97, 118, 97, 112, 114, 111, 103, 114, 109, 116, 111, 46, 99, 111, 109 };

		String decode = new String(byteArray, charset);

		System.out.println("Decoded string : " + decode);
	}

Output:

Finally, the output has different characters because all of these are from the IBM charset.

Decoded string : ¦/ÃŽ/øÊ?ÅÊ_È?Ä?_

Decoding using standard charset such as UTF-8

Charset charset_utf8 = StandardCharsets.UTF_8;

byte[] byteArray1 = { 106, 97, 118, 97, 112, 114, 111, 103, 114, 109, 116, 111, 46, 99, 111, 109 };

String decodedStrUTF8 = new String(byteArray1, charset_utf8);

System.out.println("Decoded string using UTF 8 : " + decodedStrUTF8);

Output:

Decoded string using UTF  8 : javaprogrmto.com

3.2. Using Charset.decode()

Charset class has decode() method which converts ByteBuffer to String. Below is the example on Charset.decode() method.

Invalid characters will be replaced with the default replacement character.

// creating byte array
byte[] byteArray = { 106, 97, 118, 97, 112, 114, 111, 103, 114, 109, 116, 111, 46, 99, 111, 109, 32, 63, 63, 63,
		63 };
// create charset object
Charset charset = StandardCharsets.US_ASCII;

ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
// decoding string
String output = charset.decode(byteBuffer).toString();

System.out.println("output  : " + output);

Output:

output  : javaprogrmto.com ????

3.3 Using CharsetDecoder

CharsetDecoder gives the fine-grained control and solution over the decoding process. This gives the flexibility to replace the illegal characters with the desired letter.

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;

public class CharsetDecoderDecode {

	public static void main(String[] args) throws CharacterCodingException {

		// creating byte array
		byte[] byteArray = { 106, 97, 118, 97, 112, 114, 111, 103, 114, 109, 116, 111, 46, 99, 111, 109, 32, 63, 63, 63,
				63 };

		CharsetDecoder decoder = StandardCharsets.US_ASCII.newDecoder();

		// Replacing the unmapping charset with zero's
		decoder.onMalformedInput(CodingErrorAction.IGNORE).onUnmappableCharacter(CodingErrorAction.REPLACE)
				.replaceWith("?");

		ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);

		String finalDecodedStr = decoder.decode(byteBuffer).toString();

		System.out.println("finalDecodedStr : " + finalDecodedStr);
	}
}

Output:

finalDecodedStr : javaprogrmto.com ????

3. 4 Using Java  8 Base 84 encodeToString()

Java 8 Base64 library has an encodeToString() method converts a byte array to String. Working with base. 64 api is very simple and less code.

A full example for Base 64 encoding and decoding:


  String originalString = "Welcome to javaprogramto.com";

   // create base simple encoder object
   Base64.Encoder simpleEncoder = Base64.getEncoder();

   // Encoding string using simple encode
   String encodedString = simpleEncoder.encodeToString(originalString.getBytes());

   Base64.Encoder withoutPaddingEncoder = Base64.getEncoder().withoutPadding();
   System.out.println("Encoded string : "+encodedString);

   // Create base simple decoder  object
   Base64.Decoder simpleDecoder = Base64.getDecoder();

   // Deconding the encoded string using decoder
   String decodedString = new String(simpleDecoder.decode(encodedString.getBytes()));
   System.out.println("Decoded String : "+decodedString);

4. Conclusion

In this article, you have seen how to convert byte[] array to string in java and using java 8 base 64 api.

All examples are over Github.

How to convert String to Date in java 8?

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: How To Convert String To Byte Array and Vice Versa In Java 8
How To Convert String To Byte Array and Vice Versa In Java 8
Learn how to convert String to Byte[] array in java and do it in reverse way byte array to String in java 8.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjrTs-83oeHxidpHuguXz9UuJRdpS91h5R4bmNH6FbH7EN9hd1019iAUGaBRvgkH7gESErOAzJ4XoZ_bBRazaL10uF2_4Wdd5lXIvTCR9z0Vkk3KmZEjRh1-deO8GqtDzZ4_uSUTp64apw/w640-h348/How+To+Convert+String+To+Byte+Array+and+Vice+Versa+In+Java+8.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjrTs-83oeHxidpHuguXz9UuJRdpS91h5R4bmNH6FbH7EN9hd1019iAUGaBRvgkH7gESErOAzJ4XoZ_bBRazaL10uF2_4Wdd5lXIvTCR9z0Vkk3KmZEjRh1-deO8GqtDzZ4_uSUTp64apw/s72-w640-c-h348/How+To+Convert+String+To+Byte+Array+and+Vice+Versa+In+Java+8.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/09/java-convert-string-byte-array.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/09/java-convert-string-byte-array.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content