Java字节流Base64
Base64是一种将二进制数据编码为可打印字符的编码方式,常用于在网络传输或存储数据时使用。Java提供了对Base64编码和解码的支持,可以通过字节流进行Base64操作。
Base64简介
Base64编码是一种将二进制数据转换为ASCII字符的编码方式。它将3字节的数据分为4个6位的字节,然后根据Base64字符表进行编码。编码后的数据会比原始数据稍微增加,比如3个字节编码后会变为4个字节。Base64编码不是加密算法,它可以逆向解码还原原始数据。
Base64字符表由64个字符组成,包括A-Z、a-z、0-9和"+", "/"两个特殊字符。Java中的Base64编码是按照RFC 4648规范实现的。
Java中的Base64编码和解码
Java中的Base64编码和解码可以通过java.util.Base64
类来实现。该类提供了静态方法来进行Base64编码和解码。
Base64编码
可以使用Base64.getEncoder()
方法获取Base64编码器,然后调用encodeToString(byte[] src)
方法将字节数组编码为Base64字符串。
import java.util.Base64;
public class Base64Example {
public static void main(String[] args) {
String str = "Hello, Base64!";
byte[] bytes = str.getBytes();
Base64.Encoder encoder = Base64.getEncoder();
String base64String = encoder.encodeToString(bytes);
System.out.println("Base64 encoded string: " + base64String);
}
}
上面的代码将字符串"Hello, Base64!"编码为Base64字符串,并输出结果。
Base64解码
可以使用Base64.getDecoder()
方法获取Base64解码器,然后调用decode(String src)
方法将Base64字符串解码为字节数组。
import java.util.Base64;
public class Base64Example {
public static void main(String[] args) {
String base64String = "SGVsbG8sIEJhc2U2NCE=";
Base64.Decoder decoder = Base64.getDecoder();
byte[] bytes = decoder.decode(base64String);
String str = new String(bytes);
System.out.println("Decoded string: " + str);
}
}
上面的代码将Base64字符串"SGVsbG8sIEJhc2U2NCE="解码为原始字符串,并输出结果。
Base64在实际应用中的例子
Base64编码常用于将二进制数据转换为文本数据进行传输或存储。下面是一个使用Base64编码和解码图片的示例。
import java.io.*;
import java.util.Base64;
public class ImageBase64Example {
public static void main(String[] args) {
// 读取图片文件
File imageFile = new File("example.jpg");
try {
FileInputStream fileInputStream = new FileInputStream(imageFile);
byte[] imageBytes = new byte[(int) imageFile.length()];
fileInputStream.read(imageBytes);
fileInputStream.close();
// 将图片编码为Base64字符串
Base64.Encoder encoder = Base64.getEncoder();
String base64Image = encoder.encodeToString(imageBytes);
System.out.println("Base64 encoded image: " + base64Image);
// 将Base64字符串解码为图片
Base64.Decoder decoder = Base64.getDecoder();
byte[] decodedImage = decoder.decode(base64Image);
// 写入解码后的图片文件
FileOutputStream fileOutputStream = new FileOutputStream("decoded_example.jpg");
fileOutputStream.write(decodedImage);
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上面的代码读取了一个图片文件,将其编码为Base64字符串,然后又将Base64字符串解码为图片文件。这样可以方便地在网络传输或存储中使用图片数据。
总结
Java提供了对Base64编码和解码的支持,可以通过Base64
类来进行相关操作。Base64编码是一种将二进制数据转换为ASCII字符的编码方式,适用于在网络传输或存储数据时使用。通过Base64编码和解码,可以方便地进行数据转换和传输。
stateDiagram-v2
[*] --> 编码
编码 --> 解码