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;
    }
posted @ 2022-05-06 18:07  zwbsoft  阅读(3346)  评论(0编辑  收藏  举报