Sietse Sietse - 2 months ago 13
Java Question

Get file name from URL

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 get the file name, minus the extension? So, in this example, I'm looking for something that returns
"file"
.

I can think of several ways to do this, but I'm looking for something that's easy to read and short.

Answer

Instead of reinventing the wheel, how about using Apache commons-io:

import org.apache.commons.io.FilenameUtils;

public class FilenameUtilTest {

    public static void main(String[] args) {
        String url = "http://www.example.com/some/path/to/a/file.xml";

        String baseName = FilenameUtils.getBaseName(url);
        String extension = FilenameUtils.getExtension(url);

        System.out.println("Basename : " + baseName);
        System.out.println("extension : " + extension);
    }

}