[英]Android: Faster way to compute hash
此代碼將計算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) ;
更好的方法來處理整個文件while(dis.read() != -1) ;
; 我應該怎么做?
更好的方法是大塊讀取文件。 這避免了每個字節的許多函數調用的開銷。 當然,您不想將整個文件讀入內存,因此您可以使用一個小緩沖區:
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秒鍾的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.