1. 程式人生 > 其它 >Java獲取File檔案字尾

Java獲取File檔案字尾

    /**
     * 獲取檔案字尾名
     *
     * @param file
     * @return
     */
    public static String getFileSuffix(File file) {
        if (file == null) {
            return null;
        }
        String suffix = null;
        String fileName = file.getName();
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        }
        return suffix;
    }
使用例子
    /**
     * 檔案是否是圖片
     *
     * @param file
     * @return
     */
    public static boolean IsImage(File file) {
        boolean result = false;
        //是否是圖片
        List<String> imgs = new ArrayList<String>() {{
            this.add("JPEG");
            this.add("JPG");
            this.add("GIF");
            this.add("BMP");
            this.add("PNG");
        }};
        if (imgs.contains(getFileSuffix(file).toUpperCase())) {
            result = true;
        }
        return result;
    }