java8中 把file文件和Base64进行互相转换的

开发环境:

  JDK8:

   由于之前没有接触过Base64,因此在使用的时候,虽然从网上找了一部分例子,不过 发现在项目中却不能使用,原因是自己的项目中没有对应的jar包。

后来才发现,原来在jdk1.6以后的版本中,就已经把Base64的一些方法给集成了,虽然不用重新导入jar包,不过关于Base64的一些使用方法也都改变了。

下面是我遇到了两种情况:

<1> 

将 file 转化为 Base64
 
    /**将 file 转化为 Base64*/    public static String fileToBase64(String path) {        File file = new File(path);        FileInputStream inputFile;        try {            inputFile = new FileInputStream(file);            byte[] buffer = new byte[(int) file.length()];            inputFile.read(buffer);            inputFile.close();            return Base64.getEncoder().encodeToString(buffer);        } catch (Exception e) {            throw new RuntimeException("文件路径无效\n" + e.getMessage());        }    }

<2>

将Base64 转换为file文件

    /**将Base64 转换为file文件*/
    public static boolean base64ToFile(String base64, String path) {
        byte[] buffer;
        try {
            buffer = Base64.getDecoder().decode(base64);
            FileOutputStream out = new FileOutputStream(path);
            out.write(buffer);
            out.close();
            return true;
        } catch (Exception e) {
            throw new RuntimeException("base64字符串异常或地址异常\n" + e.getMessage());
        }
    }

对以上两个方法的调用

 main方法

    public static void main(String[] args) {
        // 将文件转换为Base64
        String path1 = "D:/temp/1.pdf";
        String result = Base64deom.fileToBase64(path1);
        System.out.println("该文件的Base64:"+result);
       
        // 将Base64转换为文件
        String path = "D:/temp/copy1.pdf";
        String base64 = result;
        Boolean res = Base64deom.base64ToFile(base64, path);
        System.out.println(res);
    }


 

大功告成

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_72429728

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值