Get file name from URL

If you are making a request to download a file and want to get the file name from a URL you could append the file without the extension with the file extension or use a utility to get the file name. The challenge with either approaches is that URLs contain parameters such as www.someurl.com?foo=bar that is unaccounted for. Alternatively you could write a regex to look for the . or build a URL. The first two snippets is in case you don't need to worry about parameters while the second set in case you do need to account for them while pulling the name from an web page address.

Setup

private String IMAGE_URL = "https://www.google.com/assets/images/srpr/logo11w.png";
private String IMAGE_URL_WITH_PARAMS = "http://www.google.com/assets/images/srpr/logo11w.png?something=whatever";

Java 7 File I/O

@Test
public void fileNameUrl_java7() throws MalformedURLException,
        URISyntaxException {

    Path fileName = Paths.get(IMAGE_URL);

    assertEquals("logo11w.png", fileName.getFileName().toString());
}

Apache Commons

@Test
public void file_name_url_apache() {

    String fullFileName = FilenameUtils.getName(IMAGE_URL);

    assertEquals("logo11w.png", fullFileName.toString());
}

Get file from URL using Jersey

@Test
public void uri_with_parameters_jersey() {

    UriBuilder buildURI = UriBuilder.fromUri(IMAGE_URL_WITH_PARAMS);

    URI uri = buildURI.build();

    assertEquals("logo11w.png", Paths.get(uri.getPath()).getFileName()
            .toString());
}