Base64 Encoding and Decoding Examples in Java 8
Base64 Encoding and Decoding Examples in Java 8
In this tutorial we will discuss how to Encode and Decode using Base64 using Java 8, which now finally has native Base64 support. In other tutorials, we have already discussed using the Base64 Encode/Decode methods of the Apache Commons Codec Package as well as the how to Base64 Encoding and Decoding Examples in Java using Google Guava. Today our focus will be on using Java 8 to perform similar functions with no additional overhead.
What’s Covered
- Getting Started
- Required Libraries
- What is Base64 Encoding
- Base64 Alphabet Characters Used for Encoding (RFC 2045)
- Base64 URL and Filename Safe Alphabet Characters Used for Encoding (RFC 4648)
- Base64 Encoding/Decoding into String using Java 8
- Base64 Encoding/Decoding Java 8 Output
- Base64 Decoding from InputStream on Classpath
- Base64 Decoding from InputStream Output
- Base64 Encoding the OutputStream Writing to File
- Base64 Encoding the OutputStream Writing to File Output
Getting Started
In order to run this tutorial yourself, you will need the following:
- Java JDK 8 or greater
- Favorite IDE Spring Tool Suite (STS), Eclipse IDE or NetBeans (I happen to be using STS because it comes with a Tomcat server built-in)
- Tomcat 7 or greater or other popular container (Weblogic, Websphere, Glassfish, JBoss, VMWare vFabric, etc). For this tutorial I am using VMware vFabric tc Server Developer Edition which is essentially an enhanced Tomcat instance integrated with Spring STS
Complete Project Overview
I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

What is Base64 Encoding
Base64 is one of several encoding schemes used to encode binary data in a text based representation (ASCII) using a radix-64 representation. Although there are several other variants among them Base16 and Base32, it is Base64 which is the most prevalent and popular. The need for Base64 arose during the advent of email. During which time folks began to speculate with the possiblity of using attachments with things like images, videos or other binary data. Since STMP (Simple Mail Transfer Protocol) only supported 7-bit ASCII characters within the messages, there was a need to be able to encode this binary data and convert it into a format that was universally supported without having to affect the current infrastructure of email servers and the SMTP protocol.
This led the industry into standards like MIME (Multipurpose Internet Mail Extensions). The MIME specification supports two binary-to-text encoding schemes (Base64 and quotable-printable).
Base64 Alphabet Characters Used for Encoding (RFC 2045)
Base64 makes use of the following characters:
Characters | Description |
---|---|
[A-Z] | 26 Characters |
[a-z] | 26 Characters |
[0-9] | 10 Characters |
[+] | 1 Character (filler) |
[/] | 1 Character (filler) |
[=] | 1 Character (padding) |
Base64 URL and Filename Safe Alphabet Characters Used for Encoding (RFC 4648)
Characters | Description |
---|---|
[A-Z] | 26 Characters |
[a-z] | 26 Characters |
[0-9] | 10 Characters |
[-] | 1 Character (filler) |
[_] | 1 Character (filler) |
[=] | 1 Character (padding) |
Base64 Encoding/Decoding into String using Java 8
In this example, we will encode a String called sampleText using the Base64 encoding algorithm. We will be using the java.util.Base64 class no available in Java 8. This class implements the Base64 Content Transfer Encoding from RFC 2045 and RFC 4648. The decoder will reject data that contains characters outside of the base64 alphabet.
The Base64 class contains many static methods which will be used in our example for the encoding and the decoding. To encode our sampleText String we will use getBytes() method which returns a byte[] array for the encodeToString static method. It will return String containing the encoded data.
In decoding a previously Base64 encoded string we will use the Base64.getDecoder().decode() method and pass in the String containing the encodedText. This method returns a byte[] array containing the decoded bytes of data.
Please Note
Please ensure you DO NOT use this encoded string in URLs as it contains characters that are NOT URL safe. To ensure that it java.util.Base64 class uses the RFC 4648 alphabetic character set you must use the getUrlEncoder() static method instead of getEncoder() method.
public static void encodeDecodeJava8String() { // ---Encode Data--- String encodedText = Base64.getEncoder() .encodeToString(sampleText.getBytes()); String urlEncodedText = Base64.getUrlEncoder() .encodeToString(sampleText.getBytes()); // ---Decode Data--- byte[] decoded = Base64.getDecoder().decode(encodedText); String decodedText = new String(decoded); System.out.println("Base64 Encoding/Decoding - Java 8"); System.out.println("---------------------------------"); System.out.println("SampleText........: " + sampleText); System.out.println("Basic EncodedText.: " + encodedText); System.out.println("URL EncodedText...: " + urlEncodedText); System.out.println("DecodedText.......: " + decodedText); System.out.println(); }
Base64 Encoding/Decoding Java 8 Output
If you look closely at the two encoded text strings you will notice that BASIC encode contains a slash ‘/’ (RG8sIG9yIGRvIE5vdC4/IFRoZXJlIGlzIG5vIHRyeS4=) and the URL encoded one contains an underscore ‘_’ (RG8sIG9yIGRvIE5vdC4_IFRoZXJlIGlzIG5vIHRyeS4=) that is one of the two differences between the two character alphabets for RFC 2045 and RFC 4648.
Base64 Encoding/Decoding - Java 8 --------------------------------- SampleText........: Do, or do Not.? There is no try. Basic EncodedText.: RG8sIG9yIGRvIE5vdC4/IFRoZXJlIGlzIG5vIHRyeS4= URL EncodedText...: RG8sIG9yIGRvIE5vdC4_IFRoZXJlIGlzIG5vIHRyeS4= DecodedText.......: Do, or do Not.? There is no try.
Sample Base64 Input file (Text wrapped for blog purposes only)
V2hlbiBteSBsb3ZlIHN3ZWFycyB0aGF0IHNoZSBpcyBtYWRlIG9mIHRydXRoIEkgZG 8gYmVsaWV2ZSBoZXIsIHRob3VnaCBJIGtub3cgc2hlIGxpZXMsIFRoYXQgc2hlIG1p Z2h0IHRoaW5rIG1lIHNvbWUgdW50dXRvcpJkIHlvdXRoLCBVbmxlYXJuZWQgaW4gdG hlIHdvcmxkknMgZmFsc2Ugc3VidGxldGllcy4gVGh1cyB2YWlubHkgdGhpbmtpbmcg dGhhdCBzaGUgdGhpbmtzIG1lIHlvdW5nLCBBbHRob3VnaCBzaGUga25vd3MgbXkgZG F5cyBhcmUgcGFzdCB0aGUgYmVzdCwgU2ltcGx5IEkgY3JlZGl0IGhlciBmYWxzZSBz cGVha2luZyB0b25ndWU6IE9uIGJvdGggc2lkZXMgdGh1cyBpcyBzaW1wbGUgdHJ1dG ggc3VwcHJlc3OSZC4gQnV0IHdoZXJlZm9yZSBzYXlzIHNoZSBub3Qgc2hlIGlzIHVu anVzdD8gQW5kIHdoZXJlZm9yZSBzYXkgbm90IEkgdGhhdCBJIGFtIG9sZD8gTywgbG 92ZZJzIGJlc3QgaGFiaXQgaXMgaW4gc2VlbWluZyB0cnVzdCwgQW5kIGFnZSBpbiBs b3ZlIGxvdmVzIG5vdCB0byBoYXZlIHllYXJzIHRvbGQ6IFRoZXJlZm9yZSBJIGxpZS B3aXRoIGhlciBhbmQgc2hlIHdpdGggbWUsIEFuZCBpbiBvdXIgZmF1bHRzIGJ5IGxp ZXMgd2UgZmxhdHRlcpJkIGJlLiA=
Base64 Decoding from InputStream on Classpath
In this example we will be reading a file ‘shakespeare_b64.txt’ that contains base64 encoded data from our InputStream. To make it easier to work with streams, Java 8 has added the wrap() method which will automatically perform the encoding or decoding of the data as it arrives in the input stream. In our example below you can see that the encoded input is decoded to plain text before being outputted to the console (System.out).
public static void decodeFromFile() throws IOException { String line = null; // Since this file is in our resources folder // I will be reading the resource from stream InputStream inputStream = Base64EncodeDecodeJDK.class .getResourceAsStream("/shakespeare_b64.txt"); InputStream decInputStream = Base64.getDecoder() .wrap( inputStream ); BufferedReader reader = new BufferedReader( new InputStreamReader(decInputStream)); //Let's iterate and read all lines in the file while ((line = reader.readLine()) != null) { System.out.println(line); } decInputStream.close(); inputStream.close(); }
Base64 Decoding from InputStream Output (Text wrapped for blog purposes only)
When my love swears that she is made of truth I do believe her, though I know she lies, That she might think me some untutor’d youth, Unlearned in the world’s false subtleties. Thus vainly thinking that she thinks me young, Although she knows my days are past the best, Simply I credit her false speaking tongue: On both sides thus is simple truth suppress’d. But wherefore says she not she is unjust? And wherefore say not I that I am old? O, love’s best habit is in seeming trust, And age in love loves not to have years told: Therefore I lie with her and she with me, And in our faults by lies we flatter’d be.
Base64 Encoding the OutputStream Writing to File
In this example we will are reading a file ‘shakespeare.txt’ that is plain text from our InputStream and encode it to base64 before outputting to another file named ‘shakespeare_b64.txt’. The automatic encoding happens as a result of adding the Base64.getEncoder().wrap( outputStream ) wrapping to the outputstream. Now as we write the contents out to the file using the write.write(line) method it is automatically encoded.
public static void encodeToFile() throws IOException { String line = null; // Since this file is in our resources folder // I will be reading the resource from stream InputStream inputStream = Base64EncodeDecodeJDK.class .getResourceAsStream("/shakespeare.txt"); BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream)); // Create a file for base64 encoded text File file = new File("shakespeare_b64.txt"); OutputStream outputStream = new FileOutputStream(file); OutputStream encOutputStream = Base64.getEncoder() .wrap( outputStream ); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(encOutputStream)); //Let's iterate and read all lines in the file while ((line = reader.readLine()) != null) { writer.write(line); } writer.flush(); writer.close(); encOutputStream.close(); outputStream.close(); }
Base64 Encoding the OutputStream Writing to File Output (Text wrapped for blog purposes only)
V2hlbiBteSBsb3ZlIHN3ZWFycyB0aGF0IHNoZSBpcyBtYWRlIG9mIHRydXRoIEkgZG 8gYmVsaWV2ZSBoZXIsIHRob3VnaCBJIGtub3cgc2hlIGxpZXMsIFRoYXQgc2hlIG1p Z2h0IHRoaW5rIG1lIHNvbWUgdW50dXRvcpJkIHlvdXRoLCBVbmxlYXJuZWQgaW4gdG hlIHdvcmxkknMgZmFsc2Ugc3VidGxldGllcy4gVGh1cyB2YWlubHkgdGhpbmtpbmcg dGhhdCBzaGUgdGhpbmtzIG1lIHlvdW5nLCBBbHRob3VnaCBzaGUga25vd3MgbXkgZG F5cyBhcmUgcGFzdCB0aGUgYmVzdCwgU2ltcGx5IEkgY3JlZGl0IGhlciBmYWxzZSBz cGVha2luZyB0b25ndWU6IE9uIGJvdGggc2lkZXMgdGh1cyBpcyBzaW1wbGUgdHJ1dG ggc3VwcHJlc3OSZC4gQnV0IHdoZXJlZm9yZSBzYXlzIHNoZSBub3Qgc2hlIGlzIHVu anVzdD8gQW5kIHdoZXJlZm9yZSBzYXkgbm90IEkgdGhhdCBJIGFtIG9sZD8gTywgbG 92ZZJzIGJlc3QgaGFiaXQgaXMgaW4gc2VlbWluZyB0cnVzdCwgQW5kIGFnZSBpbiBs b3ZlIGxvdmVzIG5vdCB0byBoYXZlIHllYXJzIHRvbGQ6IFRoZXJlZm9yZSBJIGxpZS B3aXRoIGhlciBhbmQgc2hlIHdpdGggbWUsIEFuZCBpbiBvdXIgZmF1bHRzIGJ5IGxp ZXMgd2UgZmxhdHRlcpJkIGJlLiA=
Base64 Encoding/Decoding FileStream to and From files Complete Code
package com.avaldes.tutorial; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Base64; public class Base64EncodeDecodeJDK { private static String sampleText = "Do, or do Not. There is no try."; public static void main(String[] args) throws IOException { decodeFromFile(); encodeToFile(); encodeToConsole(); } public static void decodeFromFile() throws IOException { String line = null; // Since this file is in our resources folder // I will be reading the resource from stream InputStream inputStream = Base64EncodeDecodeJDK.class .getResourceAsStream("/shakespeare_b64.txt"); InputStream decInputStream = Base64.getDecoder() .wrap( inputStream ); BufferedReader reader = new BufferedReader( new InputStreamReader(decInputStream)); //Let's iterate and read all lines in the file while ((line = reader.readLine()) != null) { System.out.println(line); } decInputStream.close(); inputStream.close(); } public static void encodeToFile() throws IOException { String line = null; // Since this file is in our resources folder // I will be reading the resource from stream InputStream inputStream = Base64EncodeDecodeJDK.class .getResourceAsStream("/shakespeare.txt"); BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream)); // Create a file for base64 encoded text File file = new File("shakespeare_b64.txt"); OutputStream outputStream = new FileOutputStream(file); OutputStream encOutputStream = Base64.getEncoder() .wrap( outputStream ); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(encOutputStream)); //Let's iterate and read all lines in the file while ((line = reader.readLine()) != null) { writer.write(line); } writer.flush(); writer.close(); encOutputStream.close(); outputStream.close(); } public static void encodeToConsole() throws IOException { String line = null; // Since this file is in our resources folder // I will be reading the resource from stream InputStream inputStream = Base64EncodeDecodeJDK.class .getResourceAsStream("/shakespeare.txt"); BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream)); // Base64 Encode it to System.out (console) OutputStream encOutputStream = Base64.getEncoder() .wrap( System.out ); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(encOutputStream)); //Let's iterate and read all lines in the file while ((line = reader.readLine()) != null) { writer.write(line); } writer.flush(); writer.close(); encOutputStream.close(); } }
Download the Complete Source Code
That’s It!
I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

Core Java Related Tutorials
- Base64 Encoding and Decoding Examples in Java 8
In this tutorial we will discuss how to Encode and Decode using Base64 using Java 8, which now finally has native Base64 support. - Base64 Encoding and Decoding Examples in Java using Google Guava
This tutorial will introduce how to Encode and Decode using Base64 using Google’s Guava Project Open Source library. - Base64 Encoding and Decoding Examples in Java using Apache Commons
This tutorial will introduce Base64 encoding and decoding examples using the Apache Commons Codec library. - Custom Number Formatting in Java
In this example we will show you how to use the NumberFormat and DecimalFormat classes to format numbers using special patterns. - Custom Date Formatting in Java
In this example we will show you how to use the SimpleDateFormat class to format Date objects using special patterns to better fit the needs of the application.
Please Share Us on Social Media






Leave a Reply