package com.example.tool.controller;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* Created by LQ on 2021/9/2.
*/
public class FileToBase64 {
public static void main(String[] args){
try {
String base64Code = encodeBase64File("F:/aa.docx");
System.out.println("base64:"+base64Code);
decoderBase64File(base64Code, "F:/def.docx");
toFile(base64Code, "F:\\def.txt");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将文件转成base64 字符串
*/
public static String encodeBase64File(String path) throws Exception {
File file = new File(path);
FileInputStream inputFile = new FileInputStream(file);
// byte[] buffer = new byte[(int) file.length()];
byte[] buffer = new byte[inputFile.available()]; // 如果在网络传输中存在弊端,数据可能分批次发送
inputFile.read(buffer);
inputFile.close();
// 下面三种方式都可以将字节数组转为base64
String base64 = new BASE64Encoder().encode(buffer);// 此种方法base64存在换行
// String base64 = Base64Util.convertByteArrayToBase64String(buffer);
// String base64 = Base64.encodeBase64String(buffer);
return base64;
}
/**
* 将base64字符解码保存文件
*/
public static void decoderBase64File(String base64Code, String targetPath) throws Exception {
byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
/**
* 将base64字符保存文本文件
*/
public static void toFile(String base64Code, String targetPath) throws Exception {
byte[] buffer = base64Code.getBytes();
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
}