tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Articles > Java > Basics > How to convert Byte Array to String

How to convert Byte Array to String 

The following example shows converting Byte array to String. String class provides the following Constructors for decoding sequence of bytes into a String.

java.lang.String
  • public String(byte bytes[])
    Decodes the given byte array to String with default Charset encoding.
  • public String(byte bytes[], String charsetName)
    Decodes the given byte array to String with specified Charset name.
  • public String(byte bytes[], Charset charset)
    Decodes the given byte array to String with specified Charset.

File Name  :  
com/bethecoder/articles/basics/str2bytea/ByteArray2StringTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.articles.basics.str2bytea;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class ByteArray2StringTest {

  /**
   @param args
   @throws UnsupportedEncodingException 
   */
  public static void main(String[] argsthrows UnsupportedEncodingException {
    
    //"BE THE CODER".getBytes()
    byte [] bytes = 666932847269326779686982 };
    
    //"BE THE CODER".getBytes("UTF-16")
    byte [] bytes2 = -2, -10660690320840720
              69032067079068069082 };
    
    //"BE THE CODER".getBytes(Charset.forName("IBM420"))
    byte [] bytes3 = {-62, -5964, -29, -56, -5964, -61, -42, -60, -59, -39 };
      
    
    //Decode the bytes encoded in default charset, Charset.defaultCharset()
    String str = new String(bytes);
    System.out.println(str);
    
    //Decode the bytes encoded in UTF-16 charset
    String str2 = new String(bytes2, "UTF-16");
    System.out.println(str2);
    
    //Decode the bytes encoded in IBM420 charset
    String str3 = new String(bytes3, Charset.forName("IBM420"));
    System.out.println(str3);
    
  }

}
   

It gives the following output,
BE THE CODER
BE THE CODER
BE THE CODER


                    Print

   



Books Recommendation

 
 
bl  br