文件与base64 字符串互转

版权声明:本文为luoyong原创文章,转载请注明出处!https://blog.csdn.net/luoyong_blog https://blog.csdn.net/luoyong_blog/article/details/84253589

这是项目中用到的文件与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();
    }
}

猜你喜欢

转载自blog.csdn.net/luoyong_blog/article/details/84253589