LoginSignup
18
18

More than 5 years have passed since last update.

ファイル内容が一致しているか判定する方法(Java)

Posted at

ファイルの内容を比較し、不一致の場合は、falseを返却するロジックです。
JUnitで使うことを想定して、シンプルな方法にしてます。

一番シンプルな方法
大きなサイズのファイル比較には使えないかも。。


public boolean fileCompare(String fileA, String fileB) throws IOException {
    return Arrays.equals(Files.readAllBytes(Paths.get(fileA)), Files.readAllBytes(Paths.get(fileB)));
}

例外処理を変えてみた


public boolean fileCompare2(String fileA, String fileB) {
    boolean bRet = false;
    try {
        bRet = Arrays.equals(Files.readAllBytes(Paths.get(fileA)), Files.readAllBytes(Paths.get(fileB)));
    } catch (IOException e) {
    }
    return bRet;
}

ファイルのサイズを最初にチェックしてみた


public boolean fileCompare3(String fileA, String fileB) {
    boolean bRet = false;
    try {
        if( new File(fileA).length() != new File(fileA).length() ){
            return bRet;
        }
        byte[] byteA = Files.readAllBytes(Paths.get(fileA));
        byte[] byteB = Files.readAllBytes(Paths.get(fileB));
        bRet = Arrays.equals(byteA, byteB);
        if(!bRet){
            System.out.println(new String(byteA,"UTF-8"));
            System.out.println(new String(byteB,"UTF-8"));
        }
    } catch (IOException e) {
    }
    return bRet;
}
18
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
18