Android文件和base64互轉

在項目中需要用到文件傳輸入,有時需要將文件轉成base64字串,再將base64字串轉成字節流保存在文件了。

/**
* 將文件轉成base64 字符串
* @param path 文件路徑
* @return
* @throws Exception
*/
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 new BASE64Encoder().encode(buffer);
}
/**
* 將base64字符解碼保存文件
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static void decoderBase64File(String base64Code,String targetPath) throws Exception {
    byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
    FileOutputStream out = new FileOutputStream(targetPath);
    out.write(buffer);
    out.close();
}
/**
* 將base64字符保存文本文件
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static void toFile(String base64Code,String targetPath) throws Exception {
    byte[] buffer = base64Code.getBytes();
    FileOutputStream out = new FileOutputStream(targetPath);
    out.write(buffer);
    out.close();
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容