Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file extension in java [duplicate]

Tags:

java

file

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

like image 821
Bathakarai Avatar asked Dec 08 '22 21:12

Bathakarai


2 Answers

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.

like image 189
Hauke Ingmar Schmidt Avatar answered Dec 11 '22 11:12

Hauke Ingmar Schmidt


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.

like image 38
João Silva Avatar answered Dec 11 '22 11:12

João Silva