gpt4 book ai didi

java - JAVA 中路径名字符串的前缀和长度是什么?

转载 作者:行者123 更新时间:2023-11-30 07:59:30 29 4
gpt4 key购买 nike

File.java 使用变量作为:

private final transient int prefixLength;

并说,这是“抽象路径名的前缀”。

File.java 也有一个构造函数:

public File(String pathname) {
if (pathname == null) {
throw new NullPointerException();
}
this.path = fs.normalize(pathname);
this.prefixLength = fs.prefixLength(this.path);
}

这里是使用 fs.prefixLength() 方法设置变量 prefixLength。

变量 fs 在 File.java 中定义为:

private static final FileSystem fs = DefaultFileSystem.getFileSystem();

DefaultFileSystem 类的方法 getFileSystem() 返回 UnixFileSystem 的对象。所以方法 fs.prefixLength() 实际上调用了 UnixFileSystem 的 prefixLength() 方法。 UnixFileSystem 的 prefixLength() 方法实现为:

public int prefixLength(String pathname) {
if (pathname.length() == 0) return 0;
return (pathname.charAt(0) == '/') ? 1 : 0;
}

表示此方法将仅返回 0 或 1,具体取决于路径名的长度或路径名的第一个字符。

我的疑问是:它是什么类型的长度,它的意义是什么?

最佳答案

prefixLength 背后的想法是将文件名中指示其路径根位置的部分与文件名的其余部分分开处理:

c:\quick\brown\fox.java
^^^

上面,前缀是c:\

UNIX 实现很简单,因为只有两个初始位置是可能的 - 根 / 和当前目录(无前缀)。

显示了支持 \\c:c:\\ 的 Windows 实现下面:

public int prefixLength(String path) {
char slash = this.slash;
int n = path.length();
if (n == 0) return 0;
char c0 = path.charAt(0);
char c1 = (n > 1) ? path.charAt(1) : 0;
if (c0 == slash) {
if (c1 == slash) return 2; /* Absolute UNC pathname "\\\\foo" */
return 1; /* Drive-relative "\\foo" */
}
if (isLetter(c0) && (c1 == ':')) {
if ((n > 2) && (path.charAt(2) == slash))
return 3; /* Absolute local pathname "z:\\foo" */
return 2; /* Directory-relative "z:foo" */
}
return 0; /* Completely relative */
}

关于java - JAVA 中路径名字符串的前缀和长度是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39267785/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com