Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

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.11.0</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.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!