【问题标题】:Getting file extension from http url using Java使用 Java 从 http url 获取文件扩展名
【发布时间】:2019-03-01 13:26:26
【问题描述】:

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

但在我的情况下,我正在处理来自 http(s) url 的扩展,所以如果我有类似的东西

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

这个方法会返回svg?position=5

有没有最好的方法来处理这种情况?我的意思是不用自己写这个逻辑。

【问题讨论】:

标签: java file-extension fileutils


【解决方案1】:

您可以使用来自 JAVA 的 URL 库。在这种情况下它有很多用处。你应该这样做:

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

然后,您有很多用于“fileIneed”变量的 getter 方法。在您的情况下,“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

【讨论】:

  • 在这种情况下我也必须处理 MailformedException
  • 是的,我忘了提到这一点,但我认为这是该解决方案的唯一缺点。至少在我的情况下,我不喜欢使用正则表达式。
【解决方案2】:

如果您想要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

【讨论】:

  • 你在哪里找到这个?)我需要一个可靠的解决方案,最好来自一个知名且经过测试的库。
  • @TyulpanTyulpan 我的答案应该可以正常工作,但我将使用 Apache 库添加一个选项。
  • 我实际上在考虑类似 FilenameUtils.getExtension(new URL(url).getPath()); - 但看起来不太好,我需要处理 url 创建的异常问题
  • 我无法进一步评论。我给了你两个有效的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 2012-07-11
  • 2010-11-23
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多