package com.cheng.blzb.utils

import java.io.FileInputStream
import java.io.IOException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

object MD5Utils {

    fun getFileMD5(filePath: String?): String {
        val sb = StringBuilder()
        var md: MessageDigest? = null
        var fis: FileInputStream? = null
        val buffer = ByteArray(1024)
        var len: Int
        try {
            md = MessageDigest.getInstance("MD5")
            fis = FileInputStream(filePath)
            while (fis.read(buffer, 0, 1024).also { len = it } != -1) {
                md.update(buffer, 0, len)
            }
            val digest = md.digest()
            for (b in digest) {
                sb.append(String.format("%02x", b))
            }
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (fis != null) {
                try {
                    fis.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        return sb.toString()
    }
}