rokkonet

PC・Androidソフトウェア・アプリの開発・使い方に関するメモ

ファイル拡張子が画像かどうか判定する java

2020 May 05.


参照元 https://vacaposi.blogspot.com/2011/08/javafile.html

import java.io.File;

// https://vacaposi.blogspot.com/2011/08/javafile.html
public class CheckFileExt {
    protected boolean isImageFile(File checkedFile){

        // チェック結果
        boolean checkResultFlag = false;

        // 画像拡張子リスト
        final String[] IMAGE_EXTENSION_ARRAY = {".bmp",".gif",".jpg",".jpeg",".png"};

        // nullチェック
        if(checkedFile == null){
            return checkResultFlag;
        }

        // isFileチェック
        if(!checkedFile.isFile()){
            return checkResultFlag;
        }

        // ファイル名取得チェック
        if(checkedFile.getName() == null || checkedFile.getName().length() == 0){
            return checkResultFlag;
        }

        // ファイルの末尾が画像拡張子リストの中にあるかチェック
        for(int i=0;i<IMAGE_EXTENSION_ARRAY.length;i++){
            if (checkedFile.getName().endsWith(IMAGE_EXTENSION_ARRAY[i].toLowerCase()) ||
                    checkedFile.getName().endsWith(IMAGE_EXTENSION_ARRAY[i].toUpperCase())){
                checkResultFlag   = true;
                break;
            }
        }
        return checkResultFlag;
    }
}