DatatypeConverter单元中封装了对base64编码的一些操作
printXXX 的函数就是encode
parseXXX 的函数就是decode
String printBase64Binary(byte[]) //就是将字节数组做base64编码
byte[] parseBase64Binary(String) //就是将Base64编码后的String还原成字节数组。
注意:传给printBase64Binary 的参数是 str.getBytes(),而不是 str 本身
示例:
public static void main(String[] args) {
String str = "This is Test String_123.AbcE";
//BASE64编码与解码
String encode = DatatypeConverter.printBase64Binary(str.getBytes());
System.out.println(encode);
byte[] decode= DatatypeConverter.parseBase64Binary(encode);
System.out.println(new String(decode));
//16进制编码与解码
String encode1 = DatatypeConverter.printHexBinary(str.getBytes());
System.out.println(encode1);
byte[] decode1= DatatypeConverter.parseHexBinary(encode1);
System.out.println(new String(decode1));
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.xml.bind.DatatypeConverter;
public class Base64Utils {
/**
* 将文件转成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 DatatypeConverter.printBase64Binary(buffer);
}
/**
* 将base64字符解码保存文件
*
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static void decoderBase64File(String base64Code, String targetPath) throws Exception {
byte[] buffer = DatatypeConverter.parseBase64Binary(base64Code);
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
/**
* 将base64字符保存文本文件
*
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static void toFile(String base64Code, String targetPath) throws Exception {
byte[] buffer = base64Code.getBytes();
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
public static void main(String[] args) {
try {
String base64Code = encodeBase64File("C:/log.txt");
System.out.println(base64Code);
decoderBase64File(base64Code, "C:/log1.txt");
toFile(base64Code, "C:\\three.txt");
} catch (Exception e) {
e.printStackTrace();
}
}
}