Wednesday, February 26, 2014

How to convert byte array or char array to string in Java

public class ConvertTest {
      public static void main(String[] args) {
        try {
            String str = new String("Good Morning!");
            byte[] ba = str.getBytes();
            byte[] ba2 = str.getBytes("UTF-8");
            
            //Converting byte array to string
            String converted1 = new String(ba);
            String converted2 = new String(ba2, "UTF-8");
            System.out.println("converted1: "+converted1);
            System.out.println("converted2: "+converted2);
            
            char[] ca = str.toCharArray();
            
            //Converting char array to string
            String converted3 = new String(ca);
            String converted4 = String.valueOf(ca);
            System.out.println("converted3: "+converted3);
            System.out.println("converted4: "+converted4);
        } catch (UnsupportedEncodingException use) {
            System.out.println(use.getMessage());
        }
    }
}

References:
1.Java read from and write to a binary stream
2. Java how to read a binary file prepared by a c program

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

1 comment: