先说注意点,再看代码。
attention:
后面这个转码真的是花了我整整2天的时间。
第一:一定要穿文件到方法里面,不能直接流化后过去,这个地方也是卡死元凶,导致我后面结果死都不对。
第二:while 读文件的地方,代码我标红了,百度到的那个地方都是直接read.(buffer),亲测不行。
第三:MD5加密后一定要转为十六进制之后再进行base64
1.将文件转为base64码
public static String fileToBase64(File file) {
String base64 = null;
InputStream in = null;
try {
//将文件流化file.getInputStream()
in = new FileInputStream(file);
byte[] bytes = new byte[(int)file.getSize()];
int length = in.read(bytes);
in.close();
return new BASE64Encoder().encode(bytes );
} catch (Exception e) {
return null;
}
}
2.经过MD5加密后转为base64码
public static String getMD5Three(File file) {
2 BigInteger bi = null;
MessageDigest digest ;
3 try {
4 byte[] buffer = new byte[1024];
5 int len = 0;
InputStream fis= new FileInputStream(file);
6 MessageDigest md = MessageDigest.getInstance("MD5");
7
9 while ((len = fis.read(buffer,0,1024)) != -1) {
10 md.update(buffer, 0, len);
11 }
12 fis.close();
13 byte[] b = md.digest();
14 bi = new BigInteger(1, b);
15 } catch (Exception e) {
18 e.printStackTrace();
19 }
String string = byteToHex(digest.digest()).toUpperCase();
BASE64Encoder base64Encoder = new BASE64Encoder();
20 return base64Encoder.encode(string.getBytes());
21 }
/**
* byte数据装维十六进制字符串格式(解决转皇后首位数据0缺失的问题)
*/
private static String byteToHex(final byte[] hash){
Formatter fm = new Formatter ();
for (byte b :hash){
fm.format("%O2x",b);
}
String result = fm.toString();
fm.close();
return result;
}