从 URL 获取文件名 [英] Get file name from URL
本文介绍了从 URL 获取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Java 中,以 http://www.example.com/some/path 的形式给出一个
,获取文件名的最简单方法是什么,减去扩展名?所以,在这个例子中,我正在寻找返回 java.net.URL
或 String
/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屋!
查看全文