Base64 工具类

package com.hisun.itoppay.atc;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.bouncycastle.util.encoders.Base64;


public class Base64Utils
{
  private static final int CACHE_SIZE = 1024;


  public static byte[] decode(String base64)
    throws Exception
  {
    return Base64.decode(base64.getBytes());
  }


  public static String encode(byte[] bytes)
    throws Exception
  {
    return new String(Base64.encode(bytes));
  }


  public static String encodeFile(String filePath)
    throws Exception
  {
    byte[] bytes = fileToByte(filePath);
    return encode(bytes);
  }


  public static void decodeToFile(String filePath, String base64)
    throws Exception
  {
    byte[] bytes = decode(base64);
    byteArrayToFile(bytes, filePath);
  }


  public static byte[] fileToByte(String filePath)
    throws Exception
  {
    byte[] data = new byte[0];
    File file = new File(filePath);
    if (file.exists()) {
      FileInputStream in = new FileInputStream(file);
      ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
      byte[] cache = new byte[1024];
      int nRead = 0;
      while ((nRead = in.read(cache)) != -1) {
        out.write(cache, 0, nRead);
        out.flush();
      }
      out.close();
      in.close();
      data = out.toByteArray();
    }
    return data;
  }


  public static void byteArrayToFile(byte[] bytes, String filePath)
    throws Exception
  {
    InputStream in = new ByteArrayInputStream(bytes);
    File destFile = new File(filePath);
    if (!destFile.getParentFile().exists()) {
      destFile.getParentFile().mkdirs();
    }
    destFile.createNewFile();
    OutputStream out = new FileOutputStream(destFile);
    byte[] cache = new byte[1024];
    int nRead = 0;
    while ((nRead = in.read(cache)) != -1) {
      out.write(cache, 0, nRead);
      out.flush();
    }
    out.close();
    in.close();
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值