Java: splitting the filename into a base and extension

后端 未结 8 1944
我寻月下人不归
我寻月下人不归 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:41

    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" !)
    

提交回复
热议问题