How to get name of File object without its extension in Java?
Solution 1
If you want to implement this yourself, try this:
String name = file.getName();
int pos = name.lastIndexOf(".");
if (pos > 0) {
name = name.substring(0, pos);
}
(This variation doesn't leave you with an empty string for an input filename like ".txt". If you want the string to be empty in that case, change > 0
to >= 0
.)
You could replace the if
statement with an assignment using a conditional expression, if you thought it made your code more readable; see @Steven's answer for example. (I don't think it does ... but it is a matter of opinion.)
It is arguably a better idea to use an implementation that someone else has written and tested. Apache FilenameUtils
is a good choice; see @slachnick's Answer, and also the linked Q&A.
Solution 2
If you don't want to write this code yourself you could use Apache's FilenameUtils.
FilenameUtils.getBaseName(openFile.getName());
This will return the filename minus the path and extension.
Solution 3
I prefer to chop off before the last index of "." to be the filename. This way a file name: hello.test.txt is just hello.test
i.e.
int pos = filename.lastIndexOf(".");
String justName = pos > 0 ? filename.substring(0, pos) : filename;
You need to handle there being no extension too.
Solution 4
String#split takes a regex. "." matches any character, so you're getting an array of empty strings - one for each spot in between each pair of characters.
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)
Solution 5
There are two problems with your code...
1) Just using "." as an argument to split is being interpreted as a Rejex that you don't want. You want a literal dot. So you have to escape it...
openFile.getName().split("\\.");
2) You will incorrectly parse any file with more than one dot. The best way to do this is to search for the last dot and get the substring...
int pos = openFile.getName().lastIndexOf(".");
if(pos != -1) {
String name = openFile.getName().substring(0, pos);
}
Related videos on Youtube
MichalB
student of geoinformatics, learning Java, databases and webpages
Updated on July 09, 2022Comments
-
MichalB almost 2 years
I am trying to get name of a
File
object without its extension, e.g. getting "vegetation" when the filename is "vegetation.txt." I have tried implementing this code:openFile = fileChooser.getSelectedFile(); String[] tokens = openFile.getName().split("."); String name = tokens[0];
Unfortunately, it returns a
null
object. There is a problem just in the defining theString
object, I guess, because the methodgetName()
works correctly; it gives me the name of the file with its extension.Do you have any idea?
-
antnewbee almost 5 yearsThis should be the best answer for this question.
-
Sasha Bond over 4 yearsdoes not work if file name contains dot:
some.a-b.here.txt
-
Sasha Bond over 4 yearsdoes not work if file name contains dot:
some.a-b.here.txt