这个问题已经在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));
}
}
怎么样?
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;
}
}
}