tl;博士
去掉f1\\f2\\之前的反斜杠/-es,它会阻止/它们阻止父路径的正确解析。
示例:
以下代码使用中间路径和文件名解析给定的根路径(根据您的示例尽可能长):
public static void main(String[] args) {
String fileName = "file.txt";
// your problem was leading backslash here
Path subPath = Paths.get("f1\\f2");
// create the root paths
Path rootOnC = Paths.get("c:\\programme");
Path rootOnD = Paths.get("d:\\system");
// resolve the subpaths and the filename on the root paths
Path fullPathOnC = rootOnC.resolve(subPath).resolve(fileName);
Path fullPathOnD = rootOnD.resolve(subPath).resolve(fileName);
// print the toString representation of their absolute path
System.out.println("[C:]\t" + fullPathOnC.toAbsolutePath().toString());
System.out.println("[D:]\t" + fullPathOnD.toAbsolutePath().toString());
}
输出是这样的:
[C:] c:\programme\f1\f2\file.txt
[D:] d:\system\f1\f2\file.txt
编辑
如果你想在文件树中搜索一个已知的子路径,你可以像这样实现java.nio.file.FileVisitor:
class PathFinder implements FileVisitor<Path> {
private Path subPathToBeFound;
public PathFinder(Path subPathToBeFound) {
this.subPathToBeFound = subPathToBeFound;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.endsWith(subPathToBeFound)) {
// print the full path that contained the given subpath
System.out.println("Subpath found in " + file.toAbsolutePath().toString());
return FileVisitResult.TERMINATE;
} else {
return FileVisitResult.CONTINUE;
}
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.err.println("Visit failed: " + exc.getMessage());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
}
并以某种方式使用它类似于这个最小的例子:
public static void main(String[] args) {
String fileName = "file.txt";
// resolve the file name on the subpath
Path subPath = Paths.get("f1\\f2").resolve(fileName);
// create a file visitor
PathFinder pf = new PathFinder(subPath);
/*
* this example finds all available drives programmatically
* and walks the file tree of each one
*/
try {
for (Path root : FileSystems.getDefault().getRootDirectories()) {
System.out.println("Searching in " + root.toAbsolutePath().toString());
Files.walkFileTree(root, pf);
}
} catch (IOException e) {
e.printStackTrace();
}
}
结果可能是没有结果的完整遍历(如果驱动器上不存在子路径)或像这样的简单打印输出:
Subpath found in C:\programme\f1\f2\file.txt