Splitting filenames using system file separator symbol

前端 未结 4 1496
傲寒
傲寒 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();
    
    0 讨论(0)
  • 2021-01-01 15:50

    First of all, for this specific problem I'd recommend using the java.util.File class instead of a regex.

    That being said, the root of the problem you're running into is that the backslash character '\' signifies an escape sequence in Java regular expressions. What's happening is the regex parser is seeing the backslash and expecting there to be another character after it which would complete the escape sequence. The easiest way to get around this is to use the java.util.regex.Pattern.quote() method which will escape any special characters in the string you give it.

    With this change your code becomes:

    String splitRegex = Pattern.quote(System.getProperty("file.separator"));
    String[] splittedFileName = fileName.split(splitRegex);
    String simpleFileName = splittedFileName[splittedFileName.length-1];
    
    0 讨论(0)
  • 2021-01-01 15:55

    Another simpler way could be to do

    File f = new File(path);
    String fileName = f.getName();
    

    I believe this will work provided the paths are compatible with the platform, i.e. not sure if path "c:\file.txt" will work on Linux or not.

    0 讨论(0)
  • 2021-01-01 16:04

    When you write a file name, you should use System.getProperty("file.separator").

    When you read a file name, you could possibly have either the forward slash or the backward slash as a file separator.

    You might want to try the following:

    fileName = fileName.replace("\\", "/");
    String[] splittedFileName = fileName.split("/"));
    String simpleFileName = splittedFileName[splittedFileName.length-1];
    
    0 讨论(0)
提交回复
热议问题