我正在从网址下载一个ePub文件。
现在我想实现一个机制,通过这个机制,如果用户试图重新下载相同的文件,他应该得到警告/错误消息,并且文件不应该再次被下载。
为了实现这一点,我需要检查我的库中存在的文件的名称和用户正在尝试下载的文件的名称。
但我只有this download link,没有文件名。
如何在下载前获取文件的名称,以便与现有文件进行比较?
发布于 2012-07-20 16:52:42
在安卓系统中,你可以使用the guessFileName() method
URLUtil.guessFileName(url, null, null)
或者,Java中的简单解决方案可以是:
String fileName = url.substring(url.lastIndexOf('/') + 1);
(假设url的格式为:http://xxxxxxxxxxxxx/filename.ext
)
更新2018年3月23日
这个问题得到了很多点击率,有人评论说,我的“简单”解决方案对某些urls不起作用,所以我觉得有必要改进答案。
如果你想处理更复杂的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
发布于 2013-03-30 23:50:39
例如,尝试使用URLUtil.guessFileName(url, null, null)
。我认为这是最好的Android方式。
发布于 2014-11-08 05:46:46
保持简单:
/**
* This function will take an URL as input and return the file name.
* <p>Examples :</p>
* <ul>
* <li>http://example.com/a/b/c/test.txt -> test.txt</li>
* <li>http://example.com/ -> an empty string </li>
* <li>http://example.com/test.txt?param=value -> test.txt</li>
* <li>http://example.com/test.txt#anchor -> test.txt</li>
* </ul>
*
* @param url The input URL
* @return The URL file name
*/
public static String getFileNameFromUrl(URL url) {
String urlString = url.getFile();
return urlString.substring(urlString.lastIndexOf('/') + 1).split("\\?")[0].split("#")[0];
}
https://stackoverflow.com/questions/11575943
复制相似问题