Java Basename

From EggeWiki

Jump to: navigation, search

Ruby contains a nice build in function to get the basename of a file.

File.basename('https://www.theeggeadventure.com/wikimedia/index.php')
=> "index.php"

The handy function is not present in the JDK. Here's my Java version of the function.

	private static final Pattern BASENAME = Pattern.compile(".*?([^/]*)$");
 
	public static String basename(URL url) {
		return basename(url.getPath());
	}
 
	public static String basename(String url) {
		Matcher matcher = BASENAME.matcher(url);
		if (matcher.matches()) {
			return matcher.group(1);
		} else {
			throw new IllegalArgumentException("Can't parse " + url);
		}
	}
Personal tools
Travelling Salesman

Get the app!