Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Base64 is a text encoding scheme that provides portability for binary data between applications and platforms. Base64 can be used to store binary data in a database string column, thereby avoiding messy file operations. When combined with the data URI scheme, Base64 can be used to embed images in web pages and emails, in conformance with the HTML and Multipurpose Internet Mail Extensions (MIME) standards.

In this brief tutorial, we’ll demonstrate Java Streaming IO functions and the built-in Java Base64 class to load binary data as an InputStream and then convert it to a String.

2. Setup

Let’s look at the dependencies and the test data we’ll need for the code.

2.1. Dependencies

We’ll use the Apache IOUtils library for convenient access to testing data files by adding its dependency to our pom.xml:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.15.1</version>
</dependency>

2.2. Test Data

A binary test data file is needed here. So we’ll add a logo.png image file to our standard src/test/resources folder.

3. Converting InputStream to Base64 String

Java has built-in support for Base64 encoding and decoding in the java.util.Base64 class. So we’ll be using the static methods from there to do the heavy lifting. 

Base64.encode() method expects a byte array, and our image is in a file. Therefore, we need to first convert the file to an InputStream and then read the stream, byte-by-byte, into an array.

We’re using the IOUtils.toByteArray() method from the Apache commons-io package as a convenient alternative to the otherwise verbose Java-only approach.

First, we’ll write a simple method to generate a ‘poor man’s’ checksum:

int calculateChecksum(byte[] bytes) {
    int checksum = 0; 
    for (int index = 0; index < bytes.length; index++) {
        checksum += bytes[index]; 
    }
    return checksum; 
}

We’ll use it to compare the two arrays, verifying that they match.

The next lines open the file, convert it to a byte array, and then Base64 encode it to a String:

InputStream sourceStream  = getClass().getClassLoader().getResourceAsStream("logo.png");
byte[] sourceBytes = IOUtils.toByteArray(sourceStream);

String encodedString = Base64.getEncoder().encodeToString(sourceBytes); 
assertNotNull(encodedString);

The String looks like a block of random characters. In fact, it is not random, as we see in the verification steps:

byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
assertNotNull(decodedBytes);
assertTrue(decodedBytes.length == sourceBytes.length);
assertTrue(calculateChecksum(decodedBytes) == calculateChecksum(sourceBytes));

4. Conclusion

In this article, we’ve demonstrated the encoding of a InputStream to a Base64 string and the successful decoding of that string back into a binary array.

As always, the code presented in this article is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.