任何人都可以编写伪代码来比较Java中的字节到字节。我知道我们使用read()来读取字节到字节。但我们如何进行比较呢?
答案 0 :(得分:0)
试一试......
static boolean areFilesEqual (Path file1, Path file2) {
byte[] f1 = Files.readAllBytes(file1);
byte[] f2 = Files.readAllBytes(file2);
if (f1.length != f2.length)
return false;
else {
for (int i = 0; i < f1.length; i++) {
if (f1[i] != f2[i])
return false;
}
return true;
}
}
答案 1 :(得分:0)
我不会给你实际的代码,因为你应该能够将这个逻辑转换成真正的Java代码。如果不这样做,请先学习Java的基础知识。
boolean compareStreams(InputStream is1, InputStream is2) {
while (is1 is not end of stream && is2 is not end of stream) {
b1 = is1.read();
b2 = is2.read();
if (b1 != b2) {
return false;
}
}
if (is1 is not end of stream || is2 is not end of stream) {
// only 1 of them reached end of stream but not the other
return false;
}
return true;
}
// remember to close streams after use.
如果您了解上述逻辑,基于Java Input Stream的工作方式,它可以进一步缩小到
boolean compareStreams(InputStream is1, InputStream is2) {
b1 = 0;
b2 = 0;
do {
b1 = is1.read();
b2 = is2.read();
if (b1 != b2) {
return false;
}
} while (b1 != -1 && b2 != -1);
return true;
}