直接上示例:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.commons.codec.binary.Base64;
public class EncodeBase64Util {
/**
* 将文件转成base64 字符串
* @param path文件路径
* @return *
* @throws Exception
*/
public static String encodeBase64File(String path) throws Exception {
File file = new File(path);;
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
return new String(Base64.encodeBase64(buffer));
}
/**
* 将base64字符解码保存文件
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static void decoderBase64File(String base64Code, String targetPath)throws Exception {
byte[] buffer = Base64.decodeBase64(base64Code);
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
// public static void main(String[] args) throws Exception {
// String base64File = encodeBase64File("D:\\baiduyun\\com\\demo1516245061251.zip");
// System.out.println(base64File);
// }
}