java如何检查文件是否为图像
我想检查传递的文件是否是图像,如果不是,我想显示一条消息,指示该文件不是图像
try{
Image img = ImageIO.read(new File(name));
}catch(IOException ex)
{
valid=false;
System.out.println("The file" + name + "could not be opened, it is not an image");
}
当文件(由name
引用)不是有效的映像并且没有设置为false
时,为什么会发生这种情况?
我应该更改异常的类型吗?我已经读过关于try-catch的文章,据我所知,如果ImageIO。读取失败,异常类型为IOException将执行catch块的内容。那为什么不执行呢
是否有其他方法检查文件是否为图像
# 1 楼答案
根据Javadocs,如果文件不能作为图像读取,read返回
null
因此,您的代码应该如下所示:
# 2 楼答案
根据API
ImageIO.read(...)
返回null
,如果没有找到能够读取指定文件的注册ImageReader
,那么您可以简单地测试null
返回的结果# 3 楼答案
使用此选项获取扩展名:
并根据需要检查条件
等等