在Java中,给定一个java.net.URL
or a String
形式为http://www.example.com/some/path/to/a/file.xml
,获取文件名(减去扩展名)的最简单方法是什么?所以,在这个例子中,我正在寻找返回的东西"file"
.
我可以想出几种方法来做到这一点,但我正在寻找易于阅读且简短的内容。
与其重新发明轮子,不如使用 Apache公共IO http://commons.apache.org/proper/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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)