Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

ファイルの内容を比較し、不一致の場合は、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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした