在Java中判斷兩個文件是否一致可以通過比較它們的內容來實現。可以使用以下方法:
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileCompare {
public static boolean compareFiles(File file1, File file2) throws IOException, NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
FileInputStream fis1 = new FileInputStream(file1);
FileInputStream fis2 = new FileInputStream(file2);
byte[] dataBytes = new byte[1024];
int n = 0;
while ((n = fis1.read(dataBytes)) != -1) {
md5.update(dataBytes, 0, n);
}
byte[] md5hash1 = md5.digest();
md5.reset();
while ((n = fis2.read(dataBytes)) != -1) {
md5.update(dataBytes, 0, n);
}
byte[] md5hash2 = md5.digest();
fis1.close();
fis2.close();
return MessageDigest.isEqual(md5hash1, md5hash2);
}
public static void main(String[] args) {
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
try {
if(compareFiles(file1, file2)) {
System.out.println("The files are the same.");
} else {
System.out.println("The files are different.");
}
} catch (IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
import org.apache.commons.io.FileUtils;
public class FileCompare {
public static void main(String[] args) {
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
try {
if(FileUtils.contentEquals(file1, file2)) {
System.out.println("The files are the same.");
} else {
System.out.println("The files are different.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上兩種方法都可以判斷兩個文件是否一致,可以根據具體需求選擇合適的方法來使用。