1. 程式人生 > >檔案與base64 字串互轉

檔案與base64 字串互轉

這是專案中用到的檔案與base64字串互轉的工具,記錄於此。

import android.util.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * Created by LY on 2015/6/12.
 * encodeBase64File:(將檔案轉成base64 字串)
 * decoderBase64File:(將base64字元解碼儲存檔案)
 */

public class Base64FileUtil {

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