In order to encode a string (or a byte array) into Base64, and then decode it into its original state, one can use the following piece of code:
String s = "String to encode/decode in Base64 with DataTypeConverter";
String coded = DatatypeConverter.printBase64Binary(s.getBytes());
byte[] retr = DatatypeConverter.parseBase64Binary(coded);
System.out.println("Coded : " + coded);
System.out.println("Expected : " + s);
System.out.println("Retrieved : " + new String(retr));
System.out.println();
The generated output is:
Coded : U3RyaW5nIHRvIGVuY29kZS9kZWNvZGUgaW4gQmFzZTY0IHdpdGggRGF0YVR5cGVDb252ZXJ0ZXI=
Expected : String to encode/decode in Base64 with DataTypeConverter
Retrieved : String to encode/decode in Base64 with DataTypeConverter
For input/output streams, one can use the following:
String s = "String to encode/decode in Base64 using streams";
ByteArrayOutputStream collect = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(collect);
b64os.write(s.getBytes());
b64os.close();
byte[] ba = collect.toByteArray();
String coded = new String(ba);
InputStream is = new ByteArrayInputStream(ba);
Base64InputStream b64is = new Base64InputStream(is);
byte[] retr = IOUtils.toByteArray(b64is);
System.out.println("Coded : " + coded);
System.out.println("Expected : " + s);
System.out.println("Retrieved : " + new String(retr));
The above uses an external library to
convert the InputStream into a byte array. The generated output is:
Coded : U3RyaW5nIHRvIGVuY29kZS9kZWNvZGUgaW4gQmFzZTY0IHVzaW5nIHN0cmVhbXM=
Expected : String to encode/decode in Base64 using streams
Retrieved : String to encode/decode in Base64 using streams
The code examples are available from
Github, in the Java-Core-Examples directory.
More Java tips & tricks
here.