Kotlin计算文件MD5

    private fun calculateMD5(filePath: String): String {
        val file = File(filePath)
        val md5Digest = MessageDigest.getInstance("MD5")

        // 使用缓冲区读取文件内容
        val buffer = ByteArray(8192)
        val fis = FileInputStream(file)
        var bytesRead: Int

        while (fis.read(buffer).also { bytesRead = it } != -1) {
            md5Digest.update(buffer, 0, bytesRead)
        }

        fis.close()

        // 获取计算得到的MD5值
        val md5Bytes = md5Digest.digest()

        // 将字节数组转换为十六进制字符串表示
        val md5String = StringBuilder()
        for (i in md5Bytes.indices) {
            md5String.append(Integer.toString((md5Bytes[i].toInt() and 0xff) + 0x100, 16).substring(1))
        }

        return md5String.toString()
    }

你可能感兴趣的:(kotlin,android,开发语言)