In Java, given a java.net.URL
or a String
in the form of http://www.example.com/some/path/to/a/file.xml
, what is the easiest way to g
Keep it simple :
/**
* This function will take an URL as input and return the file name.
* Examples :
*
* - http://example.com/a/b/c/test.txt -> test.txt
* - http://example.com/ -> an empty string
* - http://example.com/test.txt?param=value -> test.txt
* - http://example.com/test.txt#anchor -> test.txt
*
*
* @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];
}