Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Tuesday, September 15, 2020

How To Convert String To Byte Array and Vice Versa 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?

No comments:

Post a Comment

Please do not add any spam links in the comments section.