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.
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.
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.
`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.
Using Bash, there's also ${file%. *} to get the filename without the extension and ${file##*.} to get the extension alone. That is, file="thisfile.
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¶m2=bla
, you could use this instead:
String url = "https://abc.xyz.com/path/somefilename.xy?param1=blie¶m2=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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With