有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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块的内容。那为什么不执行呢

是否有其他方法检查文件是否为图像


共 (3) 个答案

  1. # 1 楼答案

    根据Javadocs,如果文件不能作为图像读取,read返回null

    If no registered ImageReader claims to be able to read the resulting stream, null is returned.

    因此,您的代码应该如下所示:

    try {
        Image 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.");
    }
    
  2. # 2 楼答案

    根据API ImageIO.read(...)返回null,如果没有找到能够读取指定文件的注册ImageReader,那么您可以简单地测试null返回的结果

  3. # 3 楼答案

    使用此选项获取扩展名:

    String extension = "";
    
    int i = fileName.lastIndexOf('.');
    if (i > 0) {
        extension = fileName.substring(i+1);
    }
    

    并根据需要检查条件

    if(extension=="jpg"){
    //your code
    }
    

    等等