java将file类型base64_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);

}

大功告成

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值