Base64 encoding and decoding using Apache Commons

This code example shows how to encode a String in Base64 and then decode it back to a readable String again.
The class Base64 have both static methods and non-static methods to do the encoding and decoding. The class also have several constructors for different features and first we will use the default constructor without parameters to do our base64 encoding / decoding.

The output from the code above is an encoded String on the first line and then the decoded String on the second line:

You can also split the encoded value on several lines. To do that we use another constructor of the Base64 class that takes a number specifying how long each line should be. Below we set the line length to be 16 characters long:

The output will in this case look like this:

There are also other constructors to set for example which characters to use for line breaks. The default values for line breaks (as used above) is CRLF (or “\r\n”). There’s also a possibility to have the encoded data URL safe, so it can be used in a URL query string.

Another option is to call the static methods of the Base64 class instead of creating an instance of it and call the non-static methods. This is how it looks like when calling static methods:

The static methods have a variant that is called encodeBase64Chunked that will split the encoded data in 76 character lines. It doesn’t however have a variant to specify how long the lines should be like the non-static constructor has.

The output will then look like this:

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?