通过Base64将文件与字符串互转

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * Base64工具类
 * 
 */
public class Base64Util {

    public static String fileToBase64(File file) throws IOException {
        String strBase64 = null;
        try {
            InputStream in = new FileInputStream(file);
            // in.available()返回文件的字节长度
            byte[] bytes = new byte[in.available()];
            // 将文件中的内容读入到数组中
            in.read(bytes);
            strBase64 = encode(bytes); // 将字节流数组转换为字符串
            in.close();
        } catch (FileNotFoundException fe) {
            fe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return strBase64;
    }

    public static void base64ToFile(String strBase64, File toFile) throws IOException {
        String string = strBase64;
        ByteArrayInputStream in = null;
        FileOutputStream out = null;
        try {
            // 解码,然后将字节转换为文件
            byte[] bytes = decode(string.trim());
            // 将字符串转换为byte数组
            in = new ByteArrayInputStream(bytes);
            byte[] buffer = new byte[1024];
            out = new FileOutputStream(toFile);
            int byteread = 0;
            while ((byteread = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteread); // 文件写操作
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }finally{
            if(out!=null)
                out.close();
            if(in!=null)
                in.close();
        }
    }

    /**
     * 编码
     * 
     * @param bstr
     * @return String
     */
    public static String encode(byte[] bstr) {
    	return Base64.getEncoder().encodeToString(bstr);
    }

    /**
     * 解码
     * 
     * @param str
     * @return string
     */
    public static byte[] decode(String str) {
        return Base64.getDecoder().decode(str);
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值