1. package Base64ToArray;
  2. import java.io.*;
  3. import java.util.Base64;
  4. public class Base64ToFile {
  5. public static void main(String[] args) {
  6. String filePath = "D:/1.png";
  7. String base64 = fileToBase64(filePath);
  8. System.out.println(base64);
  9. base64StringToFile(base64, "D:", "sexy.png");
  10. }
  11. /**
  12. * Convert a file to a base64 string
  13. *
  14. * @param filePath
  15. * @return
  16. */
  17. public static String fileToBase64(String filePath) {
  18. if (filePath == null)
  19. return null;
  20. byte[] data = null;
  21. try {
  22. InputStream in = new FileInputStream(filePath);
  23. data = new byte[in.available()];
  24. in.read(data);
  25. in.close();
  26. } catch (FileNotFoundException e) {
  27. e.printStackTrace();
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. String encodedString = Base64.getEncoder().encodeToString(data);
  32. return encodedString;
  33. }
  34. /**
  35. * convert a base64 string to a file
  36. *
  37. * @param encodedString
  38. * @param filePath
  39. * @param fileName
  40. * @return
  41. */
  42. public static boolean base64StringToFile(String encodedString, String filePath, String fileName) {
  43. if (encodedString == null || filePath == null || fileName == null)
  44. return false;
  45. byte[] data = Base64.getDecoder().decode(encodedString);
  46. try {
  47. OutputStream out = new FileOutputStream(filePath + File.separator + fileName);
  48. out.write(data);
  49. out.flush();
  50. out.close();
  51. return true;
  52. } catch (FileNotFoundException e) {
  53. e.printStackTrace();
  54. } catch (IOException e) {
  55. e.printStackTrace();
  56. }
  57. return false;
  58. }
  59. }

参考