Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to extract filename from URL [duplicate]

Tags:

java

regex

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.

like image 416
amuser Avatar asked Oct 22 '14 13:10

amuser


People also ask

How do I get the filename from a URL?

The filename is the last part of the URL from the last trailing slash. For example, if the URL is http://www.example.com/dir/file.html then file. html is the file name.

What happens when you delete the file name in URL and the most important part of the URL?

Deleting a File To delete a document or image is to completely remove it from your site. If this file was linked or placed on one of your pages, once it is deleted, the link will no longer work and offer the 404 error page to the visitor and deleted images will no longer display on the pages.

How do I get filenames without an extension in Unix?

`basename` command is used to read the file name without extension from a directory or file path. Here, NAME can contain the filename or filename with full path. SUFFIX is optional and it contains the file extension part that the user wants to remove.

How do I get filename in bash?

Using Bash, there's also ${file%. *} to get the filename without the extension and ${file##*.} to get the extension alone. That is, file="thisfile.


1 Answers

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"
like image 149
Kevin Cruijssen Avatar answered Oct 01 '22 22:10

Kevin Cruijssen