package org.example;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String fileDir0 = "E:/"; // 替换为实际文件的路径
String fileDir1 = null;
Scanner scanner = new Scanner(System.in);
// 指定文件的路径
String filePath;
String fileName = null;
while (true){
System.out.println("------------------------------------");
System.out.println("请输入文件地址");
filePath = scanner.nextLine();
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(".")) + "\\"; // 替换为实际文件的路径
String outputPath = fileDir1 + fileName.substring(0, fileName.lastIndexOf(".")) + "base.txt";
File f = new File(fileDir1);
if (!f.exists()){
f.mkdirs();
}
File file1 = new File(fileDir1 + file.getName());
if (file1.exists()){
file1.delete();
}
try {
Files.copy(file.toPath(), file1.toPath());
} catch (IOException e) {
throw new RuntimeException(e);
}
FileInputStream fileInputStream = null;
FileWriter fileWriter = null;
try {
fileInputStream = new FileInputStream(filePath);
fileWriter = new FileWriter(outputPath);
String base64String = "";
byte[] buffer = new byte[1200];//buffer大小必须是3的倍数
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
// 这里处理读取的数据,例如将其转换为Base64字符串
byte[] chunk = Arrays.copyOfRange(buffer, 0, bytesRead);
base64String = Base64.getEncoder().encodeToString(chunk);
fileWriter.write(base64String);
}
}
catch (OutOfMemoryError e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("文件保存在" + outputPath);
}
}
}
base64分块编码
最新推荐文章于 2024-10-15 15:51:02 发布