Need to extract filename from URL [duplicate]

别说谁变了你拦得住时间么 提交于 2021-02-08 16:22:06

问题


I am trying to extract a file name with some specific extension from a URL. For example, I have a URL like "https://abc.xyz.com/path/somefilename.xy". I need to extract "somefilename.xy" from the above URL, and nothing else.

basically I need to write that code in my java program

I am not that good in regular expressions, so can somebody help me in that.


回答1:


You could also do it without regular expressions like so:

String url = "https://abc.xyz.com/path/somefilename.xy";
String fileName = url.substring(url.lastIndexOf('/') + 1);
// fileName is now "somefilename.xy"

EDIT (credit to @SomethingSomething): If you should also support urls with parameters, like https://abc.xyz.com/path/somefilename.xy?param1=blie&param2=bla, you could use this instead:

String url = "https://abc.xyz.com/path/somefilename.xy?param1=blie&param2=bla";
java.net.Url urlObj = new java.net.Url(url);
String urlPath = urlObj.getPath();
String fileName = urlPath.substring(urlPath.lastIndexOf('/') + 1);
// fileName is now "somefilename.xy"



回答2:


This has been done a hundred times, taken from this answer:

import org.apache.commons.io.FilenameUtils;

public class FilenameUtilTest {

    public static void main(String[] args) {
        String url = "http://www.example.com/some/path/to/a/file.xml";

        String baseName = FilenameUtils.getBaseName(url);
        String extension = FilenameUtils.getExtension(url);

        System.out.println("Basename : " + baseName);
        System.out.println("extension : " + extension);
    }

}


来源:https://stackoverflow.com/questions/26508424/need-to-extract-filename-from-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!