How to Base64 Encode a String in Java

0 min read 78 words

Quick solution

In short, you can just do this:

new String(Base64.getEncoder().encode(bytes));

Examples and an explanation

In Java 8 and above, you just need to import the Base64 class:

import java.util.Base64;

Then use the Base64 static methods as follows:

byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));

byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));

If you want to directly encode a string and get the result as an encoded string:

String encodeBytes = Base64.getEncoder()
    .encodeToString(("Your String").getBytes());
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts