我想獲得文件目錄的MD5校驗和,我已經得到了文件的算法,但是當我將它用於目錄時,結果爲空。我怎樣才能快速獲得校驗和。 以下是我對一個文件的解析(從匿名stackoverflower編輯)。如何在Android/Java中獲取文件目錄的MD5校驗和
public String fileToMD5(String filePath) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath); // Create an FileInputStream instance according to the filepath
byte[] buffer = new byte[1024]; // The buffer to read the file
MessageDigest digest = MessageDigest.getInstance("MD5"); // Get a MD5 instance
int numRead = 0; // Record how many bytes have been read
while (numRead != -1) {
numRead = inputStream.read(buffer);
if (numRead > 0)
digest.update(buffer, 0, numRead); // Update the digest
}
byte [] md5Bytes = digest.digest(); // Complete the hash computing
return convertHashToString(md5Bytes); // Call the function to convert to hex digits
} catch (Exception e) {
return null;
} finally {
if (inputStream != null) {
try {
inputStream.close(); // Close the InputStream
} catch (Exception e) { }
}
}
}
我搜索,有一些solutings:該目錄下
- 預購文件。
- 將目錄壓縮到諸如.zip或.rar之類的存檔文件中,並對其進行校驗。
- 將目錄下的所有內容轉換爲流,並進行校驗和。
我不知道是否有一些方便的解決方案。提前感謝您。
我有一些問題:1。它與文件夾下的文件列表中的順序varing? 2.您是否獲得了文件MD5的MD5校驗和而不是文件MD5? – twlkyao
1.是的,如果文件改變順序,這也會改變目錄的校驗和。 2.是的,我得到所有文件的MD5拼接在一起的md5。如果目錄MD5中的任何文件發生更改,則其md5的字符串的md5也會更改。 – Alexalex1432
我會妥協以預先排序文件並壓縮文件夾。謝謝你們一樣。 – twlkyao