1
我有一个Android应用程序,它获取zip文件的MD5校验和。我用它来比较文件与服务器上的文件。我的问题是,每次我尝试为同一个文件生成md5时,校验和是不同的。我在这里发布我的方法。你能告诉我什么是错的吗?Zip文件MD5校验和 - 每次不同
private static String fileMD5(String filePath) throws NoSuchAlgorithmException, IOException {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
MessageDigest digest = MessageDigest.getInstance("MD5");
int numRead = 0;
while (numRead != -1) {
numRead = inputStream.read(buffer);
if (numRead > 0)
digest.update(buffer, 0, numRead);
}
byte [] md5Bytes = digest.digest();
return convertHashToString(md5Bytes);
} catch (Exception e) {
return "ERROR";
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) { }
}
}
}
private static String convertHashToString(byte[] md5Bytes) {
String returnVal = "";
for (int i = 0; i < md5Bytes.length; i++) {
returnVal += Integer.toString((md5Bytes[i] & 0xff) + 0x100, 16).substring(1);
}
return returnVal;
}
我没有在代码中看到任何东西来解释为什么你会得到不同的结果。最可能的解释是您的数据与运行不同。即使您使用相同的文件名称指定该方法,但如果文件内容以任何方式在运行之间进行修改,您将得到不同的结果。 – 2015-02-06 18:43:20
你的代码确实看起来不错...我会建议先检查一下,看看你是否总是从文件中读取相同数量的字节。 – Jamie 2015-02-06 19:11:57
Okey,谢谢。我会试试:) – definera 2015-02-06 19:24:05