File.separator

API语法:

File(String pathname)
通过将给定路径名字符串转换为抽象路径名来创建一个新File实例。
public static final String separator
与系统有关的默认名称分隔符,为了方便,它被表示为一个字符串。此字符串只包含一个字符,即separatorChar
public static final char separatorChar
与系统有关的默认名称分隔符。此字段被初始化为包含系统属性 file.separator 值的第一个字符。在 UNIX 系统上,此字段的值为 '/';在 Microsoft Windows 系统上,它为 '\\'

注意:

路径名字符串与抽象路径名之间的转换与系统有关。将抽象路径名转换为路径名字符串时,每个名称与下一个名称之间用一个默认分隔符 隔开。默认名称分隔符由系统属性 file.separator 定义,可通过此类的公共静态字段 separatorseparatorChar 使其可用。将路径名字符串转换为抽象路径名时,可以使用默认名称分隔符或者底层系统支持的任何其他名称分隔符来分隔其中的名称。 

例如,我希望的文件绝对路径是E:\dev\workspace\iclass_web/conf/filterconfig.xml(计作myPath),有两种创建File的形式:

new File(myPath); // 不会报错;
new File("E:\dev\workspace\iclass_web/conf/filterconfig.xm"); //报错,应修改为new File("E:\\dev\\workspace\\iclass_web/conf/filterconfig.xml"

 我的系统是windows32位,io.File的一个字段FileSystem是一个抽象类,FileSystem被一个Win32FileSystem类继承,从而实现里面的public abstract String normalize(String path);方法。

 Win32FileSystem部分源码如下:

private final char slash;
private final char altSlash;
private final char semicolon;
public Win32FileSystem() {
    slash = ((String) AccessController.doPrivileged(new GetPropertyAction("file.separator"))).charAt(0);
    semicolon = ((String) AccessController
            .doPrivileged(new GetPropertyAction("path.separator")))
            .charAt(0);
    altSlash = (this.slash == '\\') ? '/' : '\\';
}

private boolean isSlash(char c) {
    return (c == '\\') || (c == '/');
}

private boolean isLetter(char c) {
    return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'));
}

private String slashify(String p) {
    if ((p.length() > 0) && (p.charAt(0) != slash))
        return slash + p;
    else
        return p;
}

/*
 * Check that the given pathname is normal. If not, invoke the real
 * normalizer on the part of the pathname that requires normalization. This
 * way we iterate through the whole pathname string only once.
 */
public String normalize(String path) {
    int n = path.length();
    char slash = this.slash;
    char altSlash = this.altSlash;
    char prev = 0;
    for (int i = 0; i < n; i++) {
        char c = path.charAt(i);
        if (c == altSlash)
            return normalize(path, n, (prev == slash) ? i - 1 : i);
        if ((c == slash) && (prev == slash) && (i > 1))
            return normalize(path, n, i - 1);
        if ((c == ':') && (i > 1))
            return normalize(path, n, 0);
        prev = c;
    }
    if (prev == slash)
        return normalize(path, n, n - 1);
    return path;
}
原文地址:https://www.cnblogs.com/timelyxyz/p/2584982.html