此代码将计算 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;
}
但是对于一个相当大的文件(例如,2MB 的图片),这将挂起大约 10 秒,这是一个荒谬的时间。显然有比 while(dis.read() != -1) ;
; 更好的方法来处理整个文件。我该怎么办?
最佳答案
更好的方法是以更大的 block 读取文件。这避免了每个字节的许多函数调用的开销。当然,您不想将整个文件读入内存,因此可以只使用一个小缓冲区:
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;
}
此函数立即返回,而原始函数大约需要 10 秒。
关于java - Android:计算哈希值的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23420987/