Get file name from URL

Sietse picture Sietse · Mar 3, 2009 · Viewed 199.3k times · Source

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

Real Red. picture Real Red. · Mar 3, 2009
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );

String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));