How to Detect a URL with file extension

Total Views : 98
Zoom In Zoom Out Read Later Print

This code will help you to know how you can get/check a URL have file extensions in it. we have created two method for this one of them use predefined extensions but can ignore ? or digits in last . Second method will try to get it from the URL itself.

UrlEndWithFileExt.java

package com.prodevsblog.how_to.network.url;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Optional;

public class UrlEndWithFileExt {

    public static void main(String[] args){
        System.out.println("Check with Predefined Extensions...");
        checkWithPredefined();

        System.out.println("Get From Url...");
        String ex = getExtFromUrl();
        System.out.println("Url Extension : "+ ex);
    }

    static void checkWithPredefined() {
        String[] extns = new String[] { ".html", ".php", ".jsp", ".png", ".jpg", ".jpeg" };
        try {
            String url = "http://www.prodevsblog.com/stuff.php";

            URI uri = new URI(url);
            for (String ext : extns) {
                if (uri.getPath().endsWith(ext)) {
                    System.out.println("Extension Found : " + ext);
                    break;
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    /*
    * http://www.prodevsblog.com/stuff.zip
    * http://www.prodevsblog.com/stuff.zip?123
    * http://www.prodevsblog.com/
    * http://www.prodevsblog.com/.
    */
    static String getExtFromUrl() {
        try {
            URL url = new URL("http://www.prodevsblog.com/stuff.zip");
            final String file = url.getFile();

            if (file.contains(".")) {

                final String sub = file.substring(file.lastIndexOf('.') + 1);
                if (sub.length() != 0) {
                    if (sub.contains("?")) {
                        return sub.substring(0, sub.indexOf('?'));
                    }
                    return sub;
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return "";
    }
}

Output of the code.

Output:

Check with Predefined Extensions...
Extension Found : .php
Get From Url...
Url Extension : zip

Process finished with exit code 0

See More

Latest Photos