---
title: "Java中判断文件是否是图片文件"
author: "xianbin"
date: "2014-08-17T23:20:32Z"
tags: ["Java"]
categories: ["Web前端"]
slug: "java"
draft: false
lastmod: "2014-08-17T23:20:32Z"
id: 2105324
url: "https://xianbin.iteye.com/blog/2105324"
---

使用Image读取文件时，如果是非图像文件，则会返回null。

参考代码：

```java

try {
    Image=ImageIO.read(new File(name));
    if (image == null) {
        valid = false;
        System.out.println("The file"+name+"could not be opened , it is not an image");
    }
} catch(IOException ex) {
    valid=false;
    System.out.println("The file"+name+"could not be opened , an error occurred.");
}

```