Hello,
I just want to know if java has an implemented method in order to get the extension of a given file.
well, i can have the name with file.getName() and then make a regex on it, but i would like to know if there is something more "clean".
thanks
Marcelo
Thomas Kellerer - 23 Nov 2005 10:57 GMT
> Hello,
>
[quoted text clipped - 7 lines]
>
> Marcelo
The reason there is no getExtension() is that not every platform
actually uses Extensions like e.g. Windows does (more sophisticated OS
do not need an extension to determine which type a file is)
But there is no need to use regex to get the extension:
File f = new File(....);
String name = f.getName();
int pos = name.lastIndexOf('.');
String ext = name.substring(pos+1);
Thomas
hicks@bigmailbox.net - 23 Nov 2005 11:24 GMT
> > Hello,
> >
[quoted text clipped - 20 lines]
>
> Thomas
Don't forget to handle the case where pos == -1
zero - 23 Nov 2005 12:46 GMT
hicks@bigmailbox.net wrote in news:1132745084.293191.21410
@g44g2000cwa.googlegroups.com:
>> > Hello,
>> >
[quoted text clipped - 22 lines]
>
> Don't forget to handle the case where pos == -1
Or where the '.' is the last character in the filename.
public static String getExtension(File f)
{
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1)
ext = s.substring(i+1).toLowerCase();
if(ext == null)
return "";
return ext;
}
ossie.moore@gmail.com - 23 Nov 2005 18:10 GMT
And the case where the filename ends with dot (ie, "temp." as filename)
Roedy Green - 23 Nov 2005 16:15 GMT
>I just want to know if java has an implemented method in order to get the extension of a given file.
>
>well, i can have the name with file.getName() and then make a regex on it, but i would like to know if there is something more "clean".
just use lastIndexOf to find the .
Extension is primarily a windows notion.

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.