I have a problem to get the extension of given file name. I receive 1 file URL.
It may be like
/var/www.dir/file.tar.gz OR /var/www.dir/file.exe
Now I need to split the file extension (like .tar.gz OR .exe) from the given URL. The URL is given by the user dynamically. Any one please help me out, how to solve this problem
This is not a terrible complicated task but one that reoccurs repeatedly. Looks like something that can be produced quickly by yourself - and it can. But you still should use a ready-made, tested library for this: Apache IO Tools, specifically FilenameUtils#getExtension. This way you avoid creepy bugs or inconsistencies. Plus you get a lot of other helpful, tested stuff.
Of course in the case of the double file extension you may need to use the methods more than once, as the library can not guess up to what level you need the extension(s). It is a .gz
file, only after un-gunzipping it is a .tar
file.
You could use a combination of lastIndexOf
and indexOf
:
String s = "/var/www.dir/file.tar.gz";
String file = s.substring(s.lastIndexOf("/"));
String extension = file.substring(file.indexOf(".")); // .tar.gz
DEMO.
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