Get file name from URL

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

    Urls can have parameters in the end, this

     /**
     * Getting file name from url without extension
     * @param url string
     * @return file name
     */
    public static String getFileName(String url) {
        String fileName;
        int slashIndex = url.lastIndexOf("/");
        int qIndex = url.lastIndexOf("?");
        if (qIndex > slashIndex) {//if has parameters
            fileName = url.substring(slashIndex + 1, qIndex);
        } else {
            fileName = url.substring(slashIndex + 1);
        }
        if (fileName.contains(".")) {
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
        }
    
        return fileName;
    }
    

提交回复
热议问题