package org.example;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String fileDir0 = "C:\\Users\\Public\\Downloads\\decodebase64\\"; // 替换为实际文件的路径
String fileDir1 = null;
FileOutputStream fileOutputStream = null;
String fileName = null;
while (true){
System.out.println("------------------------------------");
System.out.println("请输入base64文件地址");
String filePath = scanner.nextLine();
System.out.println("请输入解码的文件格式 0.txt 1.jpg 2.ttf 3.mp4");
String extension = scanner.nextLine();
if ("0".equals(extension)){
extension = ".txt";
} else if ("1".equals(extension)) {
extension = ".jpg";
} else if ("2".equals(extension)) {
extension = ".ttf";
} else if ("3".equals(extension)) {
extension = ".mp4";
}
try {
//假如有路径两边有"就去掉
if ('\"' == (filePath.charAt(0)) && '\"' == (filePath.charAt(filePath.length()-1))){
filePath = filePath.substring(1, filePath.length() - 1);
}
File file = new File(filePath);
fileName = file.getName();
fileDir1 = fileDir0 + fileName.substring(0, fileName.indexOf(".")) + "\\"; // 替换为实际文件的路径
File f = new File(fileDir1);
if (!f.exists()){
f.mkdirs();
}
try (FileInputStream inputStream = new FileInputStream(filePath)) {
// 创建Base64.Decoder对象
Base64.Decoder decoder = Base64.getDecoder();
byte[] buffer = new byte[1200];//解码块大小必须是4的倍数
int bytesRead;
// 逐块读取文件并解码
fileOutputStream = new FileOutputStream(fileDir1 + fileName.substring(0, fileName.indexOf(".")) + extension);
while ((bytesRead = inputStream.read(buffer)) != -1) {
byte[] bytes = new byte[bytesRead];
System.arraycopy(buffer, 0, bytes, 0, bytesRead);
// 解码Base64编码的数据
byte[] decodedData = decoder.decode(bytes);
fileOutputStream.write(decodedData);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fileOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
System.out.println("文件保存在" + fileDir1);
}
}
}
base64分块解码
最新推荐文章于 2026-01-05 17:06:32 发布
1610

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



