[英]absolutePath of file
我在我的系統中搜索一個文件,但這個文件在其他系統下可能有不同的路徑,這意味着當我搜索file.txt
它一直在 /f1/f2/file.txt 下,但對於另一個系統,它可以就像一個系統中的c:/programme/f1/f2/file.txt
但d:/system/f1/f2/file.txt
我試過這個,但它不讀取絕對路徑
String filename = "file.txt";
Path path = Paths.get("\\f1\\f2\\");
Path absPath= path.toAbsolutePath();
File file = new File(absPath, filename);
然后我只是得到c:\\f1\\f2\\file.txt
,或者是錯誤的
在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.