您的位置:首页 > 其它

Base64编码实现一---使用sun.misc.BASE64Encoder实现Base64

2017-11-03 15:42 465 查看
使用sun.misc.BASE64Encoder实现
4000
Base64

package com.zero.io.base64;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
* 使用sun.misc.BASE64Encoder实现Base64
*
*/
public class BASE64EncoderTest {

public static void main(String[] args) throws Exception {
encode("src/pexels_photo.jpeg");//11M
byte [] b = decode(encode("src/pexels_photo.jpeg"));

createBase64File("D://sun_misc_base64.jpeg",b);

}

/**
* 将文本转为字符串
* @param filePath 文件的路径
* @return String
* @throws Exception
*/
private static String encode(String filePath)  {
BufferedInputStream inputStream = null;
byte [] b = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(filePath));
b = new byte [inputStream.available()];
inputStream.read(b);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new BASE64Encoder().encode(b);
}

/**
* 将字符串转为byte[]数组
* @param fileString 文件使用encode方法转成的字符串数据
* @return byte []
* @throws Exception
*/
private static byte [] decode(String fileString) {
byte [] b = null;
try {
b =  new BASE64Decoder().decodeBuffer(fileString);
} catch (IOException e) {
e.printStackTrace();
}

return b;
}

/**
* 生成文件
* @param filepath 文件路径
* @param b
* @return
*/
public static boolean createBase64File(String filepath,byte [] b){

BufferedOutputStream bufferedOutputStream = null;
File file = null;
try {
file = new File(filepath);

if (file.exists() && file.isFile()) {
file.delete();
}

bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
bufferedOutputStream.write(b);
bufferedOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (null != bufferedOutputStream) {
try {
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  base64