用java对比两个文件是否相同代码
时间: 2024-05-11 13:14:56 浏览: 4
可以使用以下代码来比较两个文件是否相同:
```
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class CompareFiles {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
String filePath1 = "path/to/file1";
String filePath2 = "path/to/file2";
String hash1 = getHash(filePath1);
String hash2 = getHash(filePath2);
if (hash1.equals(hash2)) {
System.out.println("The two files are the same.");
} else {
System.out.println("The two files are different.");
}
}
private static String getHash(String filePath) throws IOException, NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream(filePath);
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
fis.close();
byte[] mdbytes = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
```
这段代码使用了 MD5 哈希算法来计算文件的哈希值,然后比较两个文件的哈希值是否相同。如果哈希值相同,则说明两个文件内容完全相同。