How to compare byte to byte in Java using FileInpu

2019-09-21 06:39发布

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?

2条回答
Viruses.
2楼-- · 2019-09-21 07:19

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;
    }
}
查看更多
我只想做你的唯一
3楼-- · 2019-09-21 07:21

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;
}
查看更多
登录 后发表回答