1. 程式人生 > >Android 開發例項 Base64的使用

Android 開發例項 Base64的使用

   最近在開發中,遇到了要在移動端檢視圖片或檔案如(txt,ppt...)格式,那就開作,但是寫完了之後發現了一些問題,就是儲存的檔案裡都是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);
}

/--------------------------------------------------------------------Base64解碼

/**
* 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();

}