繁体   English   中英

使用Java从http url获取文件扩展名

[英]Getting file extension from http url using Java

现在我从apache了解FilenameUtils.getExtension()了。

但就我而言,我正在处理来自http(s)url的扩展,因此,如果我有类似

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

此方法将返回svg?position=5

是否有应对这种情况的最佳方法? 我的意思是没有自己写这个逻辑。

您可以使用JAVA中的URL库。 在这种情况下,它具有很大的实用性。 您应该执行以下操作:

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

然后,您有很多用于“ fileIneed”变量的吸气剂方法。 在您的情况下,“ getPath()”将检索以下内容:

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

然后使用您正在使用的Apache库,您将获得“ svg”字符串。

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

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

如果要使用brandname®解决方案,请在剥离查询字符串(如果存在)之后考虑使用Apache方法:

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

如果您想要一种甚至不需要外部库的单行程序,则可以使用String#replaceAll考虑此选项:

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

svg

这是上面使用的正则表达式模式的解释:

.*/     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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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