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.

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

And I have to handle MailformedException as well in this case
Yep, I forgot to mention that, but I think that is the only downside of this solution. At least in my case, I don't like the use of regular expressions.
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

4 Comments

where have you find this?) I need a reliable solution, better from a well-known and tested library.
@TyulpanTyulpan My answer should work fine, but I will add an option using the Apache library.
I was actually considering something like FilenameUtils.getExtension(new URL(url).getPath()); - but looks not so great and I need to handle exception coz of url creation
I can't comment further. I have given you two valid solutions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.