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.
If you don't need to get rid of the file extension, here's a way to do it without resorting to error-prone String manipulation and without using external libraries. Works with Java 1.7+:
andy's answer redone using split():
Keep it simple :
Create an URL object from the String. When first you have an URL object there are methods to easily pull out just about any snippet of information you need.
I can strongly recommend the Javaalmanac web site which has tons of examples, but which has since moved. You might find http://exampledepot.8waytrips.com/egs/java.io/File2Uri.html interesting:
One liner:
Complete code:
Note:
URI#gePath
is already intelligent enough to strip off query parameters and the protocol's scheme. Examples: