简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM