Java Encode String to Base64 String

Tags: Java Base64

In this java tutorial we learn how to encode a String value into a Base64 String in Java programming language.

Table of contents

  1. How to Convert a String to Base64 String in Java
  2. Encode Text File to Base64 String in Java

How to Convert a String to Base64 String in Java

In Java to encode a String to Base64 we can convert it to a byte[] array and using Base64.getEncoder().encodeToString() method to encode it to a Base64 String.

String stringData = "Simple Solution";
byte[] byteData = stringData.getBytes();
String base64String = Base64.getEncoder().encodeToString(byteData);

The following Java example code to show how to convert a String into Base64 String in Java program.

StringToBase64Example1.java

import java.util.Base64;

public class StringToBase64Example1 {
    public static void main(String... args) {
        String stringData = "Simple Solution";

        // Convert a String to Base64 String
        byte[] byteData = stringData.getBytes();
        String base64String = Base64.getEncoder().encodeToString(byteData);

        System.out.println("Input String:");
        System.out.println(stringData);
        System.out.println("Base64 Encoded String:");
        System.out.println(base64String);
    }
}
The output as below.
Input String:
Simple Solution
Base64 Encoded String:
U2ltcGxlIFNvbHV0aW9u

Encode Text File to Base64 String in Java

Using the same approach above we can also convert a text file into Base64 String.

For example, we have a text file at D:\SimpleSolution\data.txt, the following Java program to show you how to convert it to a Base64 String.

StringToBase64Example2.java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class StringToBase64Example2 {
    public static void main(String... args) throws IOException {
        String fileName = "D:\\SimpleSolution\\data.txt";

        Path filePath = Paths.get(fileName);
        byte[] allBytes = Files.readAllBytes(filePath);

        String base64String = Base64.getEncoder().encodeToString(allBytes);

        System.out.println("Base64 Encoded String:");
        System.out.println(base64String);
    }
}
The output as below.
Base64 Encoded String:
U2ltcGxlIFNvbHV0aW9u

Happy Coding 😊

Java Decode Base64 String to String

Java Convert Byte Array to Base64 String