简体   繁体   English

Android:更快的哈希计算方法

[英]Android: Faster way to compute hash

This code will compute the hash of a URI: 此代码将计算URI的哈希值:

protected void ShowHash(android.net.Uri uri) {
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5");
        BufferedInputStream is = new BufferedInputStream(getContentResolver().openInputStream(uri));
        DigestInputStream dis = new DigestInputStream(is, md);
        while(dis.read() != -1) ;
        Toast.makeText(getApplicationContext(), bytesToHex(md.digest()),
                Toast.LENGTH_LONG).show();
    } catch(Exception e) {
        Toast.makeText(getApplicationContext(), e.toString(),
                Toast.LENGTH_LONG).show();
    }
    return;
}

But for a decent sized file (say, a 2MB picture), this will hang for about 10 seconds, which is a ridiculous amount of time. 但是对于一个大小合适的文件(例如2MB的图片),它将挂起大约10秒钟,这是一个荒谬的时间。 There is obviously a better way to process the whole file than while(dis.read() != -1) ; 显然,有一种比while(dis.read() != -1) ;更好的方法来处理整个文件while(dis.read() != -1) ; ; ; how should I go about it? 我应该怎么做?

A better way is to read the file in larger chunks. 更好的方法是大块读取文件。 This avoids the overhead of many function calls for each byte. 这避免了每个字节的许多函数调用的开销。 Of course, you don't want to read the entire file into memory, so you can just use a small buffer: 当然,您不想将整个文件读入内存,因此您可以使用一个小缓冲区:

protected void ShowHash(android.net.Uri uri) {
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5");
        BufferedInputStream is = new BufferedInputStream(getContentResolver().openInputStream(uri));
        DigestInputStream dis = new DigestInputStream(is, md);
        byte[] buffer = new byte[1024];
        while(dis.read(buffer, 0, buffer.length) != -1) ;
        Toast.makeText(getApplicationContext(), bytesToHex(md.digest()),
                Toast.LENGTH_LONG).show();
    } catch(Exception e) {
        Toast.makeText(getApplicationContext(), e.toString(),
                Toast.LENGTH_LONG).show();
    }
    return;
}

This function returns instantly where the original function takes around 10 seconds. 此功能会立即返回原始功能约10秒钟的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM