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.
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) throws Exception {
URL url = new URL("http://www.example.com/some/path/to/a/file.xml?foo=bar#test");
System.out.println(FilenameUtils.getBaseName(url.getPath())); // -> file
System.out.println(FilenameUtils.getExtension(url.getPath())); // -> xml
System.out.println(FilenameUtils.getName(url.getPath())); // -> file.xml
}
}
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );
String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
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+:
import java.net.URI
import java.nio.file.Paths
String url = "http://example.org/file?p=foo&q=bar"
String filename = Paths.get(new URI(url).getPath()).getFileName().toString()