Tuesday, April 23, 2024
HomeSoftware EngineeringThe best way to Base64 Encode a String in Java

The best way to Base64 Encode a String in Java


Fast resolution

In brief, you may simply do that:

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

Examples and a proof

In Java 8 and above, you simply have to import the Base64 class:

import java.util.Base64;

Then use the Base64 static strategies as follows:

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

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

If you wish to instantly encode a string and get the end result as an encoded string:

String encodeBytes = Base64.getEncoder()
    .encodeToString(("Your String").getBytes());
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments