Get file name from URL

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

    One liner:

    new File(uri.getPath).getName
    

    Complete code (in a scala REPL):

    import java.io.File
    import java.net.URI
    
    val uri = new URI("http://example.org/file.txt?whatever")
    
    new File(uri.getPath).getName
    res18: String = file.txt
    

    Note: URI#gePath is already intelligent enough to strip off query parameters and the protocol's scheme. Examples:

    new URI("http://example.org/hey/file.txt?whatever").getPath
    res20: String = /hey/file.txt
    
    new URI("hdfs:///hey/file.txt").getPath
    res21: String = /hey/file.txt
    
    new URI("file:///hey/file.txt").getPath
    res22: String = /hey/file.txt
    

提交回复
热议问题