我正在尝试使用 java.io.File
重构一些遗留代码,以使用 java.nio.file.Path
代替。
我对 Path 对绝对文件路径有更好的支持这一事实感到震惊,因为我收到的许多值都有一个前导斜杠 (/
),而它们应该表示相对路径。这样字符串连接更容易,但我试图摆脱 String
/File
来表示文件路径。
旧的行为是 new File(parent, child)
返回一个新的 File
表示
- 父目录下的子文件/目录,无论子文件/目录是否以
/
开头。
新的行为是 parent.resolve(child)
返回一个新的 Path
代表任一
- 父目录下的子文件/目录
- child 作为根(如果它以
/
开头)
我认为新方法可以使代码更简洁,但是在重构遗留应用程序时,它可能会引入微妙的错误。
使用Path
时恢复旧的(文件
)行为的最佳/最干净的方法是什么?
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
class Main {
public static void main(String[] args) {
file();
path();
}
public static void file(){
File root = new File("/root");
File relative = new File(root, "relative");
File absolute = new File(root, "/absolute");
System.out.println("File:");
System.out.println(relative.getAbsolutePath()); // prints "/root/relative"
System.out.println(absolute.getAbsolutePath()); // prints "/root/absolute"
System.out.println();
}
public static void path(){
Path root = Paths.get("/root");
Path relative = root.resolve("relative");
Path absolute = root.resolve("/absolute");
System.out.println("Path:");
System.out.println(relative.toAbsolutePath()); // prints "/root/relative"
System.out.println(absolute.toAbsolutePath()); // prints "/absolute" but should print "/root/absolute"
System.out.println();
}
}
<小时/>
基本上,我想要的是一种采用父路径和子字符串的方法,该方法返回父+子路径,无论子路径是否有前导 /
。
像这样的东西,但没有依赖于我知道配置将使用 /
(而不是 \
)的字符串操作:
private static Path resolveSafely(Path parent, String child) {
child = child.startsWith("/")
? child.substring(1)
: child;
parent.resolve(child);
}
最佳答案
我能找到的最好方法是:
Path root = Paths.get("/root");
Path relative = root.resolve("relative");
Path absolute = Paths.get(root.toString(), "/absolute");
System.out.println("Path:");
System.out.println(relative.toAbsolutePath()); // prints "/root/relative"
System.out.println(absolute.toAbsolutePath()); // prints "/root/absolute"
System.out.println();
希望这就是您所需要的。
编辑:自 Java 11 起,Path.of()
可用,并且是获取 Path 对象的推荐方法,而不是 Paths.get()
。 Check javadoc其中还指出 Paths
类可能在未来版本中被弃用。
关于java - 解析 java.nio.files.Path 时忽略前导斜杠的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60565892/