import android.text.TextUtils; import android.util.Log; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.security.MessageDigest; import java.util.UUID; public class ChangeVideoMD5Utils { private static final String TAG = ChangeVideoMD5Utils.class.getSimpleName(); /** * 更新MD5值 * * @param path 文件路径 * @return 返回新的MD5值 */ public static String updateMD5(String path) { if (TextUtils.isEmpty(path)) { return null; } //文件路径 File file = new File(path); if (!file.exists()) { return null; } //这个方法是获取MD5,下面会有 String fileMD5 = getFileMD5(file); Log.e(TAG, "updateMD5 fileMD5:" + fileMD5); //设置一个唯一的UUID添加进MD5里使得MD5值改变 return addTxtToFileBuffered(file, getUUID()); } /** * 将MD5写入文件 * * @param file 需要改变MD5的文件 * @param content 需要写入的MD5值 * @return */ private static String addTxtToFileBuffered(File file, String content) { //在文本中追加内容 BufferedWriter out = null; try { //FileOutputStream(file, true),第二个参数为true是追加内容,false是覆盖 out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true))); out.newLine();//换行 out.write(content); Log.e(TAG, "addTxtToFileBuffered content:" + content); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } //返回一个获取视频的MD5 return getFileMD5(file); } /** * 获取文件的MD5值 * * @param path 文件路径 * @return 返回MD5值 */ public static String getFileMD5(String path) { if (TextUtils.isEmpty(path)) { return null; } //文件路径 File file = new File(path); if (!file.exists()) { return null; } if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte buffer[] = new byte[1024]; int len; try { digest = MessageDigest.getInstance("MD5"); in = new FileInputStream(file); while ((len = in.read(buffer, 0, 1024)) != -1) { digest.update(buffer, 0, len); } in.close(); } catch (Exception e) { e.printStackTrace(); return null; } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16); } /** * 获取文件的MD5值 * * @param file 文件对象 * @return 返回MD5值 */ public static String getFileMD5(File file) { if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte buffer[] = new byte[1024]; int len; try { digest = MessageDigest.getInstance("MD5"); in = new FileInputStream(file); while ((len = in.read(buffer, 0, 1024)) != -1) { digest.update(buffer, 0, len); } in.close(); } catch (Exception e) { e.printStackTrace(); return null; } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16); } /** * 获取UUID值 * * @return 返回UUID值 */ public static String getUUID() { return UUID.randomUUID().toString().replace("-", ""); } }
如何使用
ChangeVideoMD5Utils.getFileMD5(path)//获取视频MD5ChangeVideoMD5Utils.updateMD5(path) //修改并保存到原文件位置