Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
15
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@Tanaaaaan

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

ファイルの内容を比較し、不一致の場合は、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;
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
15
Help us understand the problem. What are the problem?