Is there a better way to get file basename and extension than something like
File f = ... String name = f.getName(); int dot = name.lastIndexOf('.'); String base = (dot == -1) ? name : name.substring(0, dot); String extension = (dot == -1) ? "" : name.substring(dot+1);
A filename extension is typically delimited from the rest of the filename with a full stop (period), but in some systems it is separated with spaces.
Java per se handles spaces in filenames just fine with no escaping or anything. You may be trying to access a file the user running the jvm don't have access to.
I know others have mentioned String.split
, but here is a variant that only yields two tokens (the base and the extension):
String[] tokens = fileName.split("\\.(?=[^\\.]+$)");
For example:
"test.cool.awesome.txt".split("\\.(?=[^\\.]+$)");
Yields:
["test.cool.awesome", "txt"]
The regular expression tells Java to split on any period that is followed by any number of non-periods, followed by the end of input. There is only one period that matches this definition (namely, the last period).
Technically Regexically speaking, this technique is called zero-width positive lookahead.
BTW, if you want to split a path and get the full filename including but not limited to the dot extension, using a path with forward slashes,
String[] tokens = dir.split(".+?/(?=[^/]+$)");
For example:
String dir = "/foo/bar/bam/boozled"; String[] tokens = dir.split(".+?/(?=[^/]+$)"); // [ "/foo/bar/bam/" "boozled" ]
Old question but I usually use this solution:
import org.apache.commons.io.FilenameUtils; String fileName = "/abc/defg/file.txt"; String basename = FilenameUtils.getBaseName(fileName); String extension = FilenameUtils.getExtension(fileName); System.out.println(basename); // file System.out.println(extension); // txt (NOT ".txt" !)
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