Base64转换
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
public class Base64Convert {
public static String encodeBase64File(String path) {
File file = new File(path);
FileInputStream inputFile;
byte[] buffer = new byte[0];
try {
inputFile = new FileInputStream(file);
buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
} catch (IOException e) {
e.printStackTrace();
}
return new BASE64Encoder().encode(buffer);
}
public static void decoderBase64File(String base64Code, String targetPath) {
try {
byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void toFile(String base64Code, String targetPath, String decode) {
if (base64Code != null && base64Code.length() > 0) {
decode = decode == null ? "utf-8" : decode;
byte[] buffer;
try {
buffer = base64Code.getBytes(decode);
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String encodeBase64String(String str, String decode) {
byte[] b = null;
String s = null;
decode = decode == null ? "utf-8" : decode;
try {
b = str.getBytes(decode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (b != null) {
s = new BASE64Encoder().encode(b);
}
return s;
}
public static String decoderBase64String(String s, String decode) {
byte[] b;
decode = decode == null ? "utf-8" : decode;
String result = null;
if (s != null) {
BASE64Decoder decoder = new BASE64Decoder();
try {
b = decoder.decodeBuffer(s);
result = new String(b, decode);
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
}
}