Tyulpan Tyulpan
Tyulpan Tyulpan

Reputation: 764

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.

Upvotes: 1

Views: 2288

Answers (2)

Marco Marchetti
Marco Marchetti

Reputation: 187

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

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522752

If you want a brandname® solution, then consider using the Apache method after stripping off the query string, if it exists:

String url = "https://your_url/logo.svg?position=5";
url = url.replaceAll("\\?.*$", "");
String ext = FilenameUtils.getExtension(url);
System.out.println(ext);

If you want a one-liner which does not even require an external library, then consider this option using String#replaceAll:

String url = "https://your_url/logo.svg?position=5";
String ext = url.replaceAll(".*/[^.]+\\.([^?]+)\\??.*", "$1");
System.out.println(ext);

svg

Here is an explanation of the regex pattern used above:

.*/     match everything up to, and including, the LAST path separator
[^.]+   then match any number of non dots, i.e. match the filename
\.      match a dot
([^?]+) match AND capture any non ? character, which is the extension
\??.*    match an optional ? followed by the rest of the query string, if present

Upvotes: 0

Related Questions