有 Java 编程相关的问题?

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

如何通过读取Java中的URL来知道图像是否存在?

http://nichehire.com/Nichehire/upload/img_job_photo_burhan393@gmail.com.jpg

我需要通过给定的URL知道图像是否存在。 为此,我使用下面的代码。在下面的代码中,如果没有错误发生,我将返回true,如果URL不包含图像,则返回false。 但是上面给定的URL不包含图像,即使它返回true。 我的代码有问题吗

public static boolean exists(String URLName) {
    boolean result = false;
    try {
        InputStream input = (new URL(URLName)).openStream();
        result = true;
    } catch (IOException ex) {
        System.out.println("Image doesnot exits :");
    }   
    return result;
} 

共 (2) 个答案

  1. # 1 楼答案

    [已解决]此源代码运行良好

    String url1 = "https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-xft1/t39.1997-6/p200x200/851575_126362190881911_254357215_n.png";
    
    Image image = ImageIO.read(new URL(url1));
    if(image != null){
        System.out.println("IMAGE"); 
    }else{
        System.out.println("NOT IMAGE"); 
    }
    
  2. # 2 楼答案

    这是因为您假设任何返回的响应都是图像,尽管您的URL可能会返回任何内容,HTML、JSON。。什么都行