Search code examples
javafile-extensionfileutils

Getting file extension from http url using Java


Now I know about FilenameUtils.getExtension() from apache.

But in my case I'm processing extensions from http(s) urls, so in case I have something like

https://your_url/logo.svg?position=5

this method is gonna return svg?position=5

Is there the best way to handle this situation? I mean without writing this logic by myself.


Solution

  • You can use the URL library from JAVA. It has a lot of utility in this cases. You should do something like this:

    String url = "https://your_url/logo.svg?position=5";
    URL fileIneed = new URL(url);
    

    Then, you have a lot of getter methods for the "fileIneed" variable. In your case the "getPath()" will retrieve this:

    fileIneed.getPath() ---> "/logo.svg"
    

    And then use the Apache library that you are using, and you will have the "svg" String.

    FilenameUtils.getExtension(fileIneed.getPath()) ---> "svg"
    

    JAVA URL library docs >>> https://docs.oracle.com/javase/7/docs/api/java/net/URL.html