package Base64ToArray;import java.io.*;import java.util.Base64;public class Base64ToFile { public static void main(String[] args) { String filePath = "D:/1.png"; String base64 = fileToBase64(filePath); System.out.println(base64); base64StringToFile(base64, "D:", "sexy.png"); } /** * Convert a file to a base64 string * * @param filePath * @return */ public static String fileToBase64(String filePath) { if (filePath == null) return null; byte[] data = null; try { InputStream in = new FileInputStream(filePath); data = new byte[in.available()]; in.read(data); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String encodedString = Base64.getEncoder().encodeToString(data); return encodedString; } /** * convert a base64 string to a file * * @param encodedString * @param filePath * @param fileName * @return */ public static boolean base64StringToFile(String encodedString, String filePath, String fileName) { if (encodedString == null || filePath == null || fileName == null) return false; byte[] data = Base64.getDecoder().decode(encodedString); try { OutputStream out = new FileOutputStream(filePath + File.separator + fileName); out.write(data); out.flush(); out.close(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }}
参考