Splitting filenames using system file separator symbol

前端 未结 4 1521
傲寒
傲寒 2021-01-01 15:31

I have a complete file path and I want to get the file name.

I am using the following instruction:

String[] splittedFileName = fileName.split(System.         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-01 15:49

    The problem is that \ has to be escaped in order to use it as backslash within a regular expression. You should either use a splitting API which doesn't use regular expressions, or use Pattern.quote first:

    // Alternative: use Pattern.quote(File.separator)
    String pattern = Pattern.quote(System.getProperty("file.separator"));
    String[] splittedFileName = fileName.split(pattern);
    

    Or even better, use the File API for this:

    File file = new File(fileName);
    String simpleFileName = file.getName();
    

提交回复
热议问题