Base64 encoding and decoding in Java 8

Base64 encoding and decoding in Java 8

In this post we will discuss about Base64 encoding and decoding of strings in Java 8. Before Java 8, Base64 encoding was officially not supported in Java. Java 8 introduced API for Base 64 encoding and decoding. The main class to Java 8’s Base64 support is the java.util.Base64 utility class.

Java 8 provides three types of Base64 encoders. They are.

  • Basic – In this the output is mapped to characters in the Base64 Alphabet: [A-Z][a-z][0-9]+/. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.
  • URL and Filename safe – If you are to encode a string and put into URL or filename then you have to handle certain characters(specifically ‘/’,’\’ as you may be aware that these characters cannot be present in a filename) in a special way. The basic encoder cannot be used for this purpose. This URL encoder includes -_ (minus and underline) instead of +/.
  • MIME – The MIME encoder generates a Base64 encoded output using the Basic Alphabet but in a MIME friendly format: Each line of encoded output is represented in not more than 76 characters each and uses a carriage return '\r' followed immediately by a linefeed '\n' as the line separator.

Basic Encoding and decoding in Java 8

Below Java program shows basic encoding and decoding of strings using Java 8.

Below is the output of running the above program.

URL Encoding and decoding in Java 8

Below Java program shows URL encoding and decoding of strings using Java 8.

Output

As you can see from the output, the basic encoded string contains forward slash(‘/’) which cannot be used in an URL or filename. On the other hand, the URL encoded string contains underline(_) instead of forward slash.

In a similar way you can use Base64.getMimeEncoder() and Base64.getMimeDecoder() for MIME encoding and decoding.

Wrapping

Java 8 also provides support to stream in and out buffers via encoders and decoders. The bellow program shows how a FileOutputStream can be wrapped with an encoder and a FileInputStream is wrapped with a decoder.

Output of the above program.

Image of the text file created.

encoding java 8

That’s all about encoding and decoding of text using Java 8. You can also use a third party library like Apache Commons codec’s Base64 for encoding and decoding.

Post your doubts in the comments section.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.