Monday, January 23, 2017

Java encode and decode a String in Base64

The sample code here demonstrates how to encode and decode a string object in the Base64 format.

If you get a compile-time warning such as "warning: com.sun.org.apache.xerces.internal.impl.dv.util. Base64 is internal proprietary API and may be removed in a future release", you may consider to use the java.util.Base64 (java 8) or javax.sml.bind.DatatypeConverter (java 7) to avoid the warning.

1. java 8 or a later version of java

import java.util.Base64;
public class Base64Test {
    public static void main(String [] args){
        String secret = "This message is top secret";
        byte[] encoded = Base64.getEncoder().encode(secret.getBytes());
        System.out.println("encoded value is "+ new String(encoded));
     
        byte[] decoded = Base64.getDecoder().decode(encoded);
        System.out.println("Decoded value is "+new String(decoded));
   }

2. java 7 or an earlier version of java

import javax.xml.bind.DatatypeConverter;
public class Base64Test {
    public static void main(String [] args){
       String secret = "This message is top secret";
        String encoded = DatatypeConverter.printBase64Binary(secret.getBytes());
        System.out.println("encoded value is "+ encoded);
     
        byte[] decoded = DatatypeConverter.parseBase64Binary(encoded);
        System.out.println("Decoded value is "+new String(decoded));
    }
}
-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




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 for free here.

No comments:

Post a Comment