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);
I know others have mentioned
String.split, but here is a variant that only yields two tokens (the base and the extension):For example:
Yields:
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).
TechnicallyRegexically 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,
For example: