Get file name from URL

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

    public String getFileNameWithoutExtension(URL url) {
        String path = url.getPath();
    
        if (StringUtils.isBlank(path)) {
            return null;
        }
        if (StringUtils.endsWith(path, "/")) {
            //is a directory ..
            return null;
        }
    
        File file = new File(url.getPath());
        String fileNameWithExt = file.getName();
    
        int sepPosition = fileNameWithExt.lastIndexOf(".");
        String fileNameWithOutExt = null;
        if (sepPosition >= 0) {
            fileNameWithOutExt = fileNameWithExt.substring(0,sepPosition);
        }else{
            fileNameWithOutExt = fileNameWithExt;
        }
    
        return fileNameWithOutExt;
    }
    

提交回复
热议问题