Base64 String Encoding in Java
Base64 is encoding scheme that can represent binary data in ASCII string format. This is useful whenever arbitrary data needs to be passed across systems as textual data. This ensures that binary data which may have special meaning to the transport layer remains intact during transport. Encoding and storing image binary data as an XML text node is a typical usage scenario.
Original Text: This is a test string Encoded String: VGhpcyBpcyBhIHRlc3Qgc3RyaW5n
The following Java program generates a base64 encoded string for an input string. This example uses sun.misc.BASE which is part of the Java SDK but is not officially supported by Oracle.
Base64 Encoding Example in Java
// Base64 encoding in Java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import sun.misc.BASE64Encoder; public class Base64Encoder { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter a string to encode : "); String source = reader.readLine(); BASE64Encoder encoder = new BASE64Encoder(); System.out.println("Encoded string is : "+encoder.encode(source.getBytes())); } }
Another option is to use the commons codec library which I would recommend for production systems.