java 文件是否相同_java比较两个文件是否相同

第一种 使用MD5加密,比较加密结果

由于MD5加密的特性,如果文件不同的话MD5只必定不同。

ps:使用的org.springframework.util.DigestUtils

代码如下:

/**

* 比较文件是否相同(MD5版)

*

* @param file1

* @param file2

* @return

*/

public static boolean fileEqualsMD5(File file1, File file2) {

boolean result = true;

InputStream inputStream1 = null;

InputStream inputStream2 = null;

try {

inputStream1 = new FileInputStream(file1);

inputStream2 = new FileInputStream(file2);

String fileDigest1 = DigestUtils.md5DigestAsHex(inputStream1);

String fileDigest2 = DigestUtils.md5DigestAsHex(inputStream2);

// 都为空也算不同文件

if (fileDigest1 == null || !fileDigest1.equals(fileDigest2)) {

result = false;

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (inputStream1 != null) {

inputStream1.close();

}

if (inputStream2 != null) {

inputStream2.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return result;

}

第二种 直接比较byte值

因为只需要比较两个文件是否相同,所以不需要比较整个文件,只要有byte值不相同就可以判定文件不同。这样效率更高。

public static boolean fileEqualsByte(File file1, File file2) {

InputStream inputStream1 = null;

InputStream inputStream2 = null;

boolean result = true;

try {

inputStream1 = new FileInputStream(file1);

inputStream2 = new FileInputStream(file2);

if (inputStream1.available() != inputStream2.available()) {

result = false;

} else {

int c;

while ((c = inputStream1.read()) > 0) {

int c2 = inputStream2.read();

if (c2 != c) {

result = false;

break;

}

}

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

inputStream1.close();

inputStream2.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return result;

}

例子中使用的都是File对象,方法中转为了输入流。实际使用中根据具体情况灵活运用


版权声明:本文为weixin_42523718原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。