In Below example we will learn how to use Base64 Encoding using Java
Finally Java8 incorporated Base64 Encoding. Base64 is one of the common Encoding mechanism.
Syntax
Base64.getEncoder().encodeToString(textForEncoding.getBytes());
Example
import java.util.Base64;
public class Base64Encodng {
public static void main(String[] args) {
try {
String textForEncoding = "QWERTY TEXT";
String encodedString = Base64.getEncoder().encodeToString(textForEncoding.getBytes());
System.out.println(encodedString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
UVdFUlRZIFRFWFQ=
The length of output encoded String must be a multiple of 3. else the output will be padded with additional pad characters (`=`).
But we have option to encode without padding also
Syntax
Base64.getEncoder().withoutPadding().encodeToString(textForEncoding.getBytes());
Example without Padding
import java.util.Base64;
public class Base64Encodng {
public static void main(String[] args) {
try {
String textForEncoding = "QWERTY TEXT";
String encodedString = Base64.getEncoder().withoutPadding().encodeToString(textForEncoding.getBytes());
System.out.println(encodedString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
UVdFUlRZIFRFWFQ
Decoding Syntax
Base64.getDecoder().decode(encodedString.getBytes());
Example
import java.util.Base64;
public class Base64Encodng {
public static void main(String[] args) {
try {
String textForEncoding = "QWERTY TEXT";
String encodedString = Base64.getEncoder().withoutPadding().encodeToString(textForEncoding.getBytes());
System.out.println(encodedString);
byte[] decodeByte = Base64.getDecoder().decode(encodedString.getBytes());
String decodedValue=new String(decodeByte);
System.out.println(decodedValue);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
UVdFUlRZIFRFWFQ
QWERTY TEXT