Get file name from URL

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

    Keep it simple :

    /**
     * This function will take an URL as input and return the file name.
     * 

    Examples :

    *
      *
    • http://example.com/a/b/c/test.txt -> test.txt
    • *
    • http://example.com/ -> an empty string
    • *
    • http://example.com/test.txt?param=value -> test.txt
    • *
    • http://example.com/test.txt#anchor -> test.txt
    • *
    * * @param url The input URL * @return The URL file name */ public static String getFileNameFromUrl(URL url) { String urlString = url.getFile(); return urlString.substring(urlString.lastIndexOf('/') + 1).split("\\?")[0].split("#")[0]; }

提交回复
热议问题