2、通过截取url地址最后一个"/"来获取
public static String getFileName(String url) {
String filename = "";
boolean isok = false;
// 从UrlConnection中获取文件名称
try {
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
if (conn == null) {
return null;
}
Map<String, List<String>> hf = conn.getHeaderFields();
if (hf == null) {
return null;
}
Set<String> key = hf.keySet();
if (key == null) {
return null;
}
for (String skey : key) {
List<String> values = hf.get(skey);
for (String value : values) {
String result;
try {
result = new String(value.getBytes("ISO-8859-1"), "GBK");
int location = result.indexOf("filename");
if (location >= 0) {
result = result.substring(location
+ "filename".length());
filename = result
.substring(result.indexOf("=") + 1);
isok = true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}// ISO-8859-1 UTF-8 gb2312
}
if (isok) {
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 从路径中获取
if (filename == null || "".equals(filename)) {
filename = url.substring(url.lastIndexOf("/") + 1);
}
return filename;
}