一、代码
import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Base64; public class Base64Util { public static String encodeBase64File(String path) throws Exception { if (path == null) { return null; } try { byte[] b = Files.readAllBytes(Paths.get(path)); return Base64.getEncoder().encodeToString(b); } catch (IOException e) { e.printStackTrace(); } return null; } public static void base64ToFile(String destPath, String base64, String fileName) { File file = null; //创建文件目录 String filePath = destPath; File dir = new File(filePath); if (!dir.exists() && !dir.isDirectory()) { dir.mkdirs(); } BufferedOutputStream bos = null; java.io.FileOutputStream fos = null; try { byte[] bytes = Base64.getDecoder().decode(base64); file = new File(filePath + "/" + fileName); fos = new java.io.FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bytes); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }