How do I encode binary data as Base64 string?

package org.kodejava.example.commons.codec;

import org.apache.commons.codec.binary.Base64;

import java.util.Arrays;

public class Base64Encode {
    public static void main(String[] args) {
        String hello = "Hello World";

        // The encodeBase64 method take a byte[] as the parameter. The byte[]
        // can be from a simple string like in this example or it can be from
        // an image file data.
        byte[] encoded = Base64.encodeBase64(hello.getBytes());

        // Print the encoded byte array

        // Print the encoded string
        String encodedString = new String(encoded);
        System.out.println(hello + " = " + encodedString);

The result of our program:

[83, 71, 86, 115, 98, 71, 56, 103, 86, 50, 57, 121, 98, 71, 81, 61]
Hello World = SGVsbG8gV29ybGQ=

Maven Dependencies

<!-- -->

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.