Detailed explanation
Base64 is a common encoding method that converts any byte sequence to a string composed of printed characters.In the Java class library, there is a class 64 class that provides a method of implementing Base64 encoding and decoding.
Base64 encoding rule
Base64 encodes 64 character sets (A-Z, A-Z, 0-9, +, /), and converts the data blocks of each 3-byte to 4 BASE64 characters.If the original data is not a multi -byte of 3, you need to replenish the equivalent (=) at the end to maintain multiple multiple of the coding length of 4.
Operating principle
The operating principle of the base64 encoding can be briefly summarized as the following steps:
1. The data that needs to be encoded is paid in a group in a group.
2. Divide the data of each 3 -byte into four 6 -bit fragments.
3. Convert these 6 -bit fragments to the corresponding base64 character.
4. If the data is not a double -byte of 3, add the corresponding number of 0 to the end and add an equal number (=).
5. Stitch all the conversion characters together to get the final base64 encoding result.
Java code example
The following example shows how to use Base64 in Java for encoding and decoding:
import java.util.Base64;
public class Base64Example {
public static void main(String[] args) {
String Originaltext = "Hello, Base64!"; // Original string
// Code
String encodedText = Base64.getEncoder().encodeToString(originalText.getBytes());
System.out.println("Encoded Text: " + encodedText);
// decoding
byte[] decodedBytes = Base64.getDecoder().decode(encodedText);
String decodedText = new String(decodedBytes);
System.out.println("Decoded Text: " + decodedText);
}
}
Run the above code will output the following results:
Encoded Text: SGVsbG8sIEJhc2U2NCE=
Decoded Text: Hello, Base64!
In an example, first convert the original string to byte array, and then use the `Getencoder ()` method of Base64 to encode, and convert the byte array to the Base64 -encoded string.Then, use the Base64 category `GetDecoder ()` method to decode the encoded string to obtain the original byte array and convert it into a string.
By using the Base64 in the Java class library, Java developers can easily implement the base64 encoding and decoding in order to transmit and store safely when processing the data.