在Java中,你可以使用java.util.Base64类来对Base64编码的字符串进行解码,并将解码后的字节数组转换为字节流:
示例代码
1、解码Base64字符串为字节数组
import java.util.Base64;
public class Base64Example {
public static void main(String[] args) {
// 假设这是你的Base64编码的字符串
String base64EncodedString = "SGVsbG8gV29ybGQh"; // 例如,编码后的"Hello World!"
// 使用Base64解码
byte[] decodedBytes = Base64.getDecoder().decode(base64EncodedString);
// 输出解码后的字节数组
System.out.println("Decoded bytes:");
for (byte b : decodedBytes) {
System.out.format("%02X ", b); // 打印每个字节的十六进制表示
}
}
}
2、将字节数组转换为字节流(例如,InputStream)
如果你需要将解码后的字节数组转换为字节流(例如,InputStream),你可以使用ByteArrayInputStream类。以下是如何做到这一点的示例:
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Base64;
public class Base64ToInputStreamExample {
public static void main(String[] args) {
// 假设这是你的Base64编码的字符串
String base64EncodedString = "SGVsbG8gV29ybGQh"; // 例如,编码后的"Hello World!"
// 使用Base64解码为字节数组
byte[] decodedBytes = Base64.getDecoder().decode(base64EncodedString);
// 将字节数组转换为InputStream
InputStream inputStream = new ByteArrayInputStream(decodedBytes);
// 示例:读取并打印InputStream的内容(可选)
int data;
while ((data = inputStream.read()) != -1) {
System.out.print((char) data); // 打印每个字符
}
}
}
在这个示例中,ByteArrayInputStream被用来将字节数组转换为一个InputStream对象,这使得你可以像处理任何其他输入流一样处理这些数据。这在处理需要InputStream作为参数的API时特别有用。
230

被折叠的 条评论
为什么被折叠?



