Java8中文件轉Base64和Base64轉文件


文章轉載自: https://blog.csdn.net/ynzcxx/article/details/78592598

  

有幾個項目中,都需要將圖片或者數字證書的文件轉為Base64,昨天寫代碼的時候,發現在jdk8中本就含有關於Base64的API。

從此后不再需要其他的jar包來轉換Base64了!!!

據說是JDK8加入的。


先是將文件轉為Base64:

public String encryptToBase64(String filePath) {
      if (filePath == null) {
           return null;
         }
   try {
        byte[] b = Files.readAllBytes(Paths.get(filePath));
        return Base64.getEncoder().encodeToString(b);
   } catch (IOException e) {
         e.printStackTrace();
   }
      return null;
}

 

Files、Paths類是JDK7里加入的,讀取文件不再需要調用IO包里的FileInputStream,簡單便捷。
字符串參數filePath是文件的路徑。

首先是將文件讀成二進制碼,然后通過Base64.getEncoder().encodeToString()方法將二進制碼轉換為Base64值。


然后是將Base64轉為文件:

public String decryptByBase64(String base64, String filePath) {
        if (base64 == null && filePath == null) {
              return "生成文件失敗,請給出相應的數據。";
        }
       try {
            Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64),StandardOpenOption.CREATE);
       } catch (IOException e) {
           e.printStackTrace();
       }
       return "指定路徑下生成文件成功!";
}

 


字符串參數base64指的是文件的Base64值,filePath是指的文件將要保存的位置。
通過Files.write()方法輕松將文件寫入指定位置,不再調用FileOutStream方法。

第三個參數StandardOpenOption.CREATE是處理文件的方式,我設置的是不管路徑下有或沒有,都創建這個文件,有則覆蓋。

在StandardOpenOption類中有很多參數可調用,不再累贅。


免責聲明!

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



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