Get file name from URL

前端 未结 27 1604
[愿得一人]
[愿得一人] 2020-11-28 02:24

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 g

27条回答
  •  再見小時候
    2020-11-28 03:21

    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
        }
    
    }
    

提交回复
热议问题