Java: splitting the filename into a base and extension

后端 未结 8 1897
我寻月下人不归
我寻月下人不归 2020-11-27 12:25

Is there a better way to get file basename and extension than something like

File f = ...
String name = f.getName();
int dot = name.lastIndexOf(\'.\');
Strin         


        
相关标签:
8条回答
  • 2020-11-27 12:55

    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" ] 
    
    0 讨论(0)
  • 2020-11-27 12:59

    Maybe you could use String#split

    To answer your comment:

    I'm not sure if there can be more than one . in a filename, but whatever, even if there are more dots you can use the split. Consider e.g. that:

    String input = "boo.and.foo";
    
    String[] result = input.split(".");
    

    This will return an array containing:

    { "boo", "and", "foo" }
    

    So you will know that the last index in the array is the extension and all others are the base.

    0 讨论(0)
提交回复
热议问题