这个问题已在7年前提出过,但我不能再添加答案了,因为它已经关闭了。
所以这不是一个问题 - 这是一个解决方案建议: 从Java 1.7开始,这可以是一个单一的内容:
public class FilesComparator {
public static boolean filesEquals(Path f1, Path f2) throws IOException {
return Arrays.equals(Files.readAllBytes(f1), Files.readAllBytes(f2));
}
}
答案 0 :(得分:0)
这个怎么样?
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FilesComparator {
public static boolean isEquals(File f1, File f2) throws IOException {
if (f1.length() != f2.length()) {
return false;
}
try (InputStream f1Is = new BufferedInputStream(new FileInputStream(f1)); // or just new FileInputStream(f1) if you don't want to cache some bytes and want to make a native call for each byte
InputStream f2Is = new BufferedInputStream(new FileInputStream(f2))) {
int f1CurrentByte;
int f2CurrentByte;
while ((f1CurrentByte = f1Is.read()) != -1 && (f2CurrentByte = f2Is.read()) != -1) {
if (f1CurrentByte != f2CurrentByte) {
return false;
}
}
return true;
}
}
}