文件與base64相互轉換


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();
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM