LoginSignup
0
1

Kotlinのファイル比較関数

Posted at

問題点

ファイル比較方法が多く、適切な関数の調査に時間がかかる
(また、古いバージョンの関数を使用した記事が上位にヒットすることも問題である)

解決策

本記事では、以下の場合に使用するファイル比較関数を紹介する
また、逐次更新し、最新の比較関数を紹介し続けたい(願望)

  1. ファイルのバイナリ情報が一致するか
  2. 画像イメージが一致するか

1. ファイルのバイナリ情報が同様であるか

■ FileUtiles.contentEquals
(org.apache.commons.io ライブラリ)

// Fileクラスを比較する
val checkFlag = FilesUtiles.contentEquals(file1, file2)

■ contentEquals
(Kotlin専用 標準ライブラリ)

// 各ファイルのバイト配列を作成
val byteArray1 = Files.readAllBytes(path1)
val byteArray2 = Files.readAllBytes(path2)

// バイト配列を比較する
val checkFlag = byteArray1.contentEquals(byteArray2)

2. 画像イメージが一致するか

■ image.getRGB
(javax.imageio.ImageIO ライブラリ)

val checkFlag: boolean = false

// 画像ファイルを取得する
val image_1 = ImageIO.read(Files.newInputStream(path1))
val image_2 = ImageIO.read(Files.newInputStream(path2))

// RGBを取得する
val pixel_1 = image.getRGB(x軸, y軸)
val red_1 = pixel_1 shr 16 and 0xff
val green_1 = pixel_1 shr 8 and 0xff
val blue_1 = pixel_1 and 0xff

val pixel_2 = image.getRGB(x軸、y軸)
val red_2 = pixel_2 shr 16 and 0xff
val green_2 = pixel_2 shr 8 and 0xff
val blue_2 = pixel_2 and 0xff

// 比較処理
if (red_1 == red_2
    && green_1 == green_2
    && blue_1 == blue_2) {

    // 一致する
    checkFlag = true
}

0
1
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
0
1