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.
This should about cut it (i'll leave the error handling to you):
If you want to get only the filename from a java.net.URL (not including any query parameters), you could use the following function:
For example, this input URL:
Would be translated to this output String:
The
Url
object in urllib allows you to access the path's unescaped filename. Here are some examples:Instead of reinventing the wheel, how about using Apache commons-io:
Beyond the all advanced methods, my simple trick is
StringTokenizer
: