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 decoder = Base64.getDecoder();
byte[] buffer = new byte[1200];
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);
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);
}
}
}