Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format by translating it into a radix-64 representation. It is commonly used for include small images in HTML, CSS, or JavaScript, or anything else that is part of a text file.
Java provides the java.util.Base64
class for encoding and decoding Base64 data. The Base64
class provides several static methods for encoding and decoding data, such as encode()
, decode()
, encodeToString()
, and decodeToString()
.
Here is an example of how to use the Base64
class to encode and decode data in Java:
import java.util.Base64; public class Base64Example { public static void main(String[] args) { // original data String original = "Hello, World!"; System.out.println("Original data: " + original); // encode data String encoded = Base64.getEncoder().encodeToString(original.getBytes()); System.out.println("Encoded data: " + encoded); // decode data String decoded = new String(Base64.getDecoder().decode(encoded)); System.out.println("Decoded data: " + decoded); } }
In this example, the main()
method encodes the string "Hello, World!" using the encodeToString()
method of the Base64.Encoder
class, and then decodes the encoded string using the decode()
method of the Base64.Decoder
class.
To run the example, create a new Java class and copy the code into it. Run the class using the java
command. The output should be:
Original data: Hello, World! Encoded data: SGVsbG8sIFdvcmxkIQ== Decoded data: Hello, World!
The Base64
class also provides several other methods for encoding and decoding data, such as encode()
, decode()
, encodeToString()
, and decodeToString()
. You can use these methods depending on your specific requirements.