Java Network How to - Detect a URL with file extension








Question

We would like to know how to detect a URL with file extension.

Answer

import java.net.URI;
//from  w  w  w.ja  v  a 2  s .  c  om
public class Main {
  public static void main(String... args) throws Exception {
    String url = "http://www.java2s.com/Tutorials/Java/Algorithms_How_to/index.htm";
    URI u = new URI(url);
    for (String ext : new String[] { ".png", ".pdf", ".jpg", ".html","htm" }) {
      if (u.getPath().endsWith(ext)) {
        System.out.println("Yeap");
        break;
      }
    }
  }
}

The code above generates the following result.