Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: splitting the filename into a base and extension

Tags:

java

file

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); 
like image 971
Jason S Avatar asked Dec 28 '10 12:12

Jason S


People also ask

What separates filename and extension?

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.

Can Java file names have 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.


2 Answers

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" ]  
like image 94
Adam Paynter Avatar answered Oct 25 '22 08:10

Adam Paynter


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" !) 
like image 43
Oibaf it Avatar answered Oct 25 '22 06:10

Oibaf it