can anyone write pseudocode to compare byte to byte in Java. I understand that we use read() to read byte to byte. but how do we do the comparison?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Give this a shot...
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;
}
}
回答2:
I will not give you the actual code, because you should have the ability to translate this logic to real Java code. If you do not, learn basics of Java first.
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.
If you understand the above logic, base on the way Java Input Stream works, it can be further shrunk to
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;
}