You can encode data as Base64 in Java using the java.util.Base64 class, introduced in Java 8 as part of the Java SE standard library. Here's how you can encode data as Base64 using this class:
import java.util.Base64; public class Base64EncodingExample { public static void main(String[] args) { // Encode a string as Base64 String originalString = "Hello, Base64!"; byte[] originalBytes = originalString.getBytes(); // Encoding String encodedString = Base64.getEncoder().encodeToString(originalBytes); System.out.println("Encoded String: " + encodedString); // Decode the Base64-encoded string byte[] decodedBytes = Base64.getDecoder().decode(encodedString); String decodedString = new String(decodedBytes); System.out.println("Decoded String: " + decodedString); } } In this example:
We first encode the string "Hello, Base64!" into a byte array using getBytes().
We use the Base64.getEncoder().encodeToString() method to encode the byte array as a Base64 string.
We decode the Base64-encoded string back into a byte array using Base64.getDecoder().decode().
Finally, we convert the byte array back to a string using new String(decodedBytes) to obtain the original string.
The Base64 class provides both encoding and decoding methods, making it easy to work with Base64-encoded data in Java. This is useful when you need to encode binary data, such as images or files, for transmission or storage as text.
message-passing pentaho transition floor fft listbox bootstrap-datetimepicker submit-button one-time-password getelementbyid