android 文件轉base64,Base64轉文件

在項目中需要用到文件傳輸入,爲了傳輸方便最好的辦法是將文件轉成base64字串,再將base64字串轉成字節流保存在文件了。
不過這種做法的雖然簡單,但還是要根據實際需要進行選擇;弊端是不能轉太大的文件,文件太大會造成效率上的問題。具體多大,筆者沒有做深入研究和實際測試。如有興趣,可以自己深入研究測試。

需要導入 import android.util.Base64;
/**
* encodeBase64File:(將文件轉成base64 字符串). <br/>
* @author [email protected]
* @param path 文件路徑
* @return
* @throws Exception
* @since JDK 1.6
*/
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()];
inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeToString(buffer,Base64.DEFAULT);
}
--------------------------可以加我微信號:googlecao 進行交流------------------------
/**
* decoderBase64File:(將base64字符解碼保存文件). <br/>
* @author [email protected]
* @param base64Code 編碼後的字串
* @param savePath  文件保存路徑
* @throws Exception
* @since JDK 1.6
*/
public static void decoderBase64File(String base64Code,String savePath) throws Exception {
//byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
byte[] buffer =Base64.decode(base64Code, Base64.DEFAULT);
FileOutputStream out = new FileOutputStream(savePath);
out.write(buffer);
out.close();

}


          微笑如果你覺得此文章對你有用,給我點動力,請我喝杯奶茶咯微笑


發佈了30 篇原創文章 · 獲贊 29 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章