我正在从URL下载ePub文件。
现在,我想实现一种机制,如果用户尝试重新下载相同的文件,他应该收到警告/错误消息,并且不应再次下载文件。
要实现此目的,我需要将库中存在的文件的名称与用户尝试下载的文件的名称进行检查。
但是我只有this download link,而没有文件名。
如何在下载之前获取文件名,以便将其与现有文件进行比较?
最佳答案
在android中,您可以使用the guessFileName() method:
URLUtil.guessFileName(url, null, null)
另外,Java中的简单解决方案可以是:
String fileName = url.substring(url.lastIndexOf('/') + 1);
(假设您的网址格式为:
http://xxxxxxxxxxxxx/filename.ext
)更新2018年3月23日
这个问题很受欢迎,有人评论说我的“简单”解决方案不适用于某些网址,因此我觉得有必要改进答案。
如果您想处理更复杂的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