1

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.

Tyulpan Tyulpan
  • 724
  • 1
  • 7
  • 17
  • Possible duplicate of [How to determine the file extension of a file from a uri](https://stackoverflow.com/questions/3234090/how-to-determine-the-file-extension-of-a-file-from-a-uri). – Tim Biegeleisen Mar 01 '19 at 13:47

2 Answers2

3

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

Marco Marchetti
  • 187
  • 1
  • 6
  • 14
0

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
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360