Difference between File.separator and slash in paths

后端 未结 14 1221
执笔经年
执笔经年 2020-11-22 13:15

What is the difference between using File.separator and a normal / in a Java Path-String?

In contrast to double backslash \\\\

相关标签:
14条回答
  • 2020-11-22 13:46

    Using File.separator made Ubuntu generate files with "\" on it's name instead of directories. Maybe I am being lazy with how I am making files(and directories) and could have avoided it, regardless, use "/" every time to avoid files with "\" on it's name

    0 讨论(0)
  • 2020-11-22 13:48

    OK let's inspect some code.
    File.java lines 428 to 435 in File.<init>:

    String p = uri.getPath();
    if (p.equals(""))
        throw new IllegalArgumentException("URI path component is empty");
    
    // Okay, now initialize
    p = fs.fromURIPath(p);
    if (File.separatorChar != '/')
    p = p.replace('/', File.separatorChar);
    

    And let's read fs/*(FileSystem)*/.fromURIPath() docs:

    java.io.FileSystem
    public abstract String fromURIPath(String path)
    Post-process the given URI path string if necessary. This is used on win32, e.g., to transform "/c:/foo" into "c:/foo". The path string still has slash separators; code in the File class will translate them after this method returns.

    This means FileSystem.fromURIPath() does post processing on URI path only in Windows, and because in the next line:

    p = p.replace('/', File.separatorChar);
    

    It replaces each '/' with system dependent seperatorChar, you can always be sure that '/' is safe in every OS.

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