画像ファイルの比較
比較元ファイル
素材はPhotoACから拝借しました。
コピー元画像:PCを持つ女性
コピーしたファイルとの比較(True)
コピー元ファイルをコピーしただけのファイル。
バイナリデータに差異が無いため、比較結果はTrueになる想定。
比較元ファイルをわずかに編集して比較(False)
コピー元ファイルをコピーした後、わずかに編集したもの。
顔の右側にある、小さな黒いドットが編集箇所。
編集したため、比較結果はFalseになる想定。
別ファイルとの比較(False)
存在しないファイルの場合(False)
存在しないファイル名を指定する。
IOExceptionでキャッチされる想定。
ソースコード
画像ファイルはデスクトップ上の「files」フォルダ内に格納。
Main.java
package samples.compare;
public class Main {
public static void main(String...strings) {
// 比較元ファイル
String woman_1 = "C:\\\\Users\\user\\Desktop\\files\\woman_1.jpg";
// 比較対象ファイル
String woman_1_copy = "C:\\\\Users\\user\\Desktop\\files\\woman_1_copy.jpg";
String woman_1_edit = "C:\\\\Users\\user\\Desktop\\files\\woman_1_edit.jpg";
String woman_2 = "C:\\\\Users\\user\\Desktop\\files\\woman_2.jpg";
String errer = "C:\\\\Users\\user\\Desktop\\files\\errer.jpg";
// インスタンス生成
FileCompare fc_copy = new FileCompare(woman_1, woman_1_copy);
FileCompare fc_edit = new FileCompare(woman_1, woman_1_edit);
FileCompare fc_2 = new FileCompare(woman_1, woman_2);
FileCompare fc_errer = new FileCompare(woman_1, errer);
// 比較結果を表示
System.out.println("woman_1 compare to woman_1_copy : " + fc_copy.fileCompare() );
System.out.println("woman_1 compare to woman_1_edit : " + fc_edit.fileCompare() );
System.out.println("woman_1 compare to woman_2 : " + fc_2.fileCompare() );
System.out.println("woman_1 compare to errer : " + fc_errer.fileCompare() );
}
}
FileCompare.java
package samples.compare;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class FileCompare {
private String source;
private String destination;
public FileCompare(String source, String destination) {
this.source = source ;
this.destination = destination;
}
public boolean fileCompare() {
try {
return Arrays.equals(Files.readAllBytes(Paths.get(source)), Files.readAllBytes(Paths.get(destination)));
} catch (IOException e) {
e.printStackTrace();
System.out.println("ファイルの読込に失敗しました。");
}
return false;
}
}
実行結果
想定通り、コピーしたファイル以外はすべてFlaseになっています。
また、存在しないファイル名を指定した場合、IOExceptionがthrowされました。
woman_1 compare to woman_1_copy : true
woman_1 compare to woman_1_edit : false
woman_1 compare to woman_2 : false
java.nio.file.NoSuchFileException: C:\Users\user\Desktop\files\errer.jpg
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.Files.readAllBytes(Unknown Source)
at samples.compare.FileCompare.fileCompare(FileCompare.java:19)
at samples.compare.Main.main(Main.java:21)
ファイルの読込に失敗しました。
woman_1 compare to errer : false