簡體   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