Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

extract the extension of a file

Status
Not open for further replies.

skarosi

Programmer
Jan 25, 2004
140
GR
Hi all,
i am using fileChooser to find a file and save the address to a String. how can i get just the extension of the file?
i tried with a conjuction of subString and indexOf, but if there are more than one '.' on the address i get the wrong substring. obviously i cant just say
subString(length-4,length);
cos for files with more than 3 characters on the extensions, such as *.java, will not work.
any help?
also, is it possible to set the home directory on the fileChooser window? it always opens on the "my documents" directory (for windows at least) even though the file is on a subfolder

cheers
 
One way to get a file extenstion purely from the name of the file would be like this :

Code:
	String filename = "abc.txt";
	String[] parts = filename.split("\\.");
	String ext;

	if (parts.length < 2) {
		ext = filename;
	} else {
		ext = parts[parts.length -1];
	}
	System.out.println(ext);

This would also work if you had "abc.tmp.txt" etc.

--------------------------------------------------
Free Database Connection Pooling Software
 
thanks man, this did just the trick.
so split is splitting the string to substrings between the character u want. thats cool, never new that command
thanks again
 
Be careful.

In a file with no extension, that will return the name of the file.

Cheers,

Dian
 
Another way to do it, could be:

public String getExtension(String fileName) {
int i = fileName.lastIndexOf(".") + 1;
return i == 0 ? "" : fileName.substring(i);
}

Ciao,

Tom
 
If indexOf was giving you the wrong dot, you could use lastIndexOf instead, to get the position of the last dot in the filename.
 
thanks for the heads up Diancecht. i fixed that now, if the file has no extension i set it to " ", so it is blank.#

i didnt know that lastIndexOf existed, now i already made it the other way. thanks though. it was great help
 
It's well worth having a quick look through the API Documentation whenever you've some free time - particularly for classes you'll be using frequently (like String). Even if you don't need the methods now, it's good to know what's available to you later on.
 
i know the API and have used it frequently over the years.
it is just that i havent looked on all the methods or classes.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top