Skip to content

How to Base64 Encode a String in Java

Quick solution

In short, you can just do this:

new String(Base64.getEncoder().encode(bytes));
Code language: Java (java)

Examples and an explanation

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

import java.util.Base64;
Code language: Java (java)

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));
Code language: Java (java)

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

String encodeBytes = Base64.getEncoder() .encodeToString(("Your String").getBytes());
Code language: Java (java)

See also  Square Matrix Multiplication in Java
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x