Get file name from URL

前端 未结 27 1624
[愿得一人]
[愿得一人] 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:08

    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()
    

提交回复
热议问题