Ответ 1
В Android вы можете использовать метод guessFileName():
URLUtil.guessFileName(url, null, null)
В качестве альтернативы, упрощенное решение в Java может быть:
String fileName = url.substring(url.lastIndexOf('/') + 1);
(Предполагается, что ваш URL-адрес имеет формат: http://xxxxxxxxxxxxx/filename.ext
)
ОБНОВЛЕНИЕ 23 марта 2018
Этот вопрос получает много просмотров, и кто-то прокомментировал, что мое "простое" решение не работает с определенными URL-адресами, поэтому я почувствовал необходимость улучшить ответ.
Если вы хотите работать с более сложным шаблоном URL, ниже приведен пример решения. Это становится довольно сложным довольно быстро, и я уверен, что есть некоторые странные случаи, которые мое решение все еще не может обработать, но тем не менее здесь это идет:
public static String getFileNameFromURL(String url) {
if (url == null) {
return "";
}
try {
URL resource = new URL(url);
String host = resource.getHost();
if (host.length() > 0 && url.endsWith(host)) {
// handle ...example.com
return "";
}
}
catch(MalformedURLException e) {
return "";
}
int startIndex = url.lastIndexOf('/') + 1;
int length = url.length();
// find end index for ?
int lastQMPos = url.lastIndexOf('?');
if (lastQMPos == -1) {
lastQMPos = length;
}
// find end index for #
int lastHashPos = url.lastIndexOf('#');
if (lastHashPos == -1) {
lastHashPos = length;
}
// calculate the end index
int endIndex = Math.min(lastQMPos, lastHashPos);
return url.substring(startIndex, endIndex);
}
Этот метод может обрабатывать следующие типы ввода:
Input: "null" Output: ""
Input: "" Output: ""
Input: "file:///home/user/test.html" Output: "test.html"
Input: "file:///home/user/test.html?id=902" Output: "test.html"
Input: "file:///home/user/test.html#footer" Output: "test.html"
Input: "http://example.com" Output: ""
Input: "http://www.example.com" Output: ""
Input: "http://www.example.txt" Output: ""
Input: "http://example.com/" Output: ""
Input: "http://example.com/a/b/c/test.html" Output: "test.html"
Input: "http://example.com/a/b/c/test.html?param=value" Output: "test.html"
Input: "http://example.com/a/b/c/test.html#anchor" Output: "test.html"
Input: "http://example.com/a/b/c/test.html#anchor?param=value" Output: "test.html"
Вы можете найти весь исходный код здесь: https://ideone.com/uFWxTL