从URL获取文件名 [英] Get file name from URL
本文介绍了从URL获取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中,给出 java.net.URL
或 String
,格式为 http://www.example.com/some/path/to/a/file.xml
,获取文件名的最简单方法是什么,减去扩展名?所以,在这个例子中,我正在寻找返回file
的东西。
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.
推荐答案
如何使用Apache commons-io :
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
}
}
这篇关于从URL获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文