Wednesday, 22 May 2019

Java: Convert byte array to string


String class provides below constructors to construct byte array to string.

public String(byte bytes[])
Convert the byte array to string by using platform default character encoding.

public String(byte bytes[], String charsetName)
public String(byte bytes[], Charset charset)
Convert the byte array to string by using the specified character encoding.

Example
byte[] input = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 };
String str = new String(input);
str = new String(input, StandardCharsets.UTF_8);

App.java
package com.sample.app;

import java.nio.charset.StandardCharsets;

public class App {

 public static void main(String args[]) {
  byte[] input = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 };
  String str = new String(input);
  System.out.println(str);

  str = new String(input, StandardCharsets.UTF_8);
  System.out.println(str);
 }
}

Output
Hello World
Hello World


You may like

No comments:

Post a Comment