java 文件与base64_java 将本地文件或网络文件与base64互相转换

一:将网络文件转为Base64

将文件转为base64

public static String fileToBase64(String url){

int byteread = 0;

String total = null;

byte[] totalbyte = new byte[0];

try {

URL url = new URL(url);

URLConnection conn = url.openConnection();

InputStream inStream = conn.getInputStream();

byte[] buffer = new byte[1204];

while ((byteread = inStream.read(buffer)) != -1) {

//拼接流,这样写是保证文件不会被篡改

totalbyte = byteMerger(totalbyte,buffer,byteread);

}

inStream.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return Base64.encodeBase64String(totalbyte)

}

将base转为文件

public static void base64ToFile(String base64, String filePath) {

try {

byte[] bytes = Base64.decodeBase64(base64);

//base解密

File videoFile = new File(filePath);

//输入文件

FileOutputStream fos = new FileOutputStream(videoFile);

fos.write(bytes, 0, bytes.length);

fos.flush();

fos.close();

} catch (IOException e) {

}

}

二:将本地文件转Base64

转Base64

public static String videoToBase64(File videofilePath) {

long size = videofilePath.length();

byte[] imageByte = new byte[(int) size];

FileInputStream fs = null;

BufferedInputStream bis = null;

try {

fs = new FileInputStream(videofilePath);

bis = new BufferedInputStream(fs);

bis.read(imageByte);

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (bis != null) {

try {

bis.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (fs != null) {

try {

fs.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return Base64.encodeBase64String(imageByte);

}

将Base64转文件

public static void base64ToFile(String base64, String filePath) {

try {

byte[] bytes = Base64.decodeBase64(base64);

//base解密

File videoFile = new File(filePath);

//输入文件

FileOutputStream fos = new FileOutputStream(videoFile);

fos.write(bytes, 0, bytes.length);

fos.flush();

fos.close();

} catch (IOException e) {

}

}

注意:

在将文件转Base64字符时,如果使用sun下的BASE64Encoder时会导致转换出来的Base64自动换行,原因是RFC2045中有规定Base64一行不能超过76字符,超过则添加回车换行符所以导致转换出来的Base64字符会出现换行,解决方法是使用Apache的 commons-codec.jar,Base64.encodeBase64String(byte[])得到的Base64字符不会出现换行

commons-codec   1.4版本时也会出现换行,使用1.8时不会出现换行,其他版本没有测试

commons-codec

commons-codec

1.8

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值