【问题标题】:absolutePath of file文件的绝对路径
【发布时间】:2020-01-16 09:40:30
【问题描述】:

我在我的系统中搜索一个文件,但这个文件在其他系统下可能有不同的路径,这意味着当我搜索 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,或者它是错误的

【问题讨论】:

    标签: java file path


    【解决方案1】:

    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
    

    【讨论】:

    • 感谢您的回答,但我不必给出根本原因,也许我会在 f1/f2/file.txt 位于 G:/windows/f1/f2/file 下的另一个系统上工作.txt 例如。我的路径中有一部分是 /f1/f2/file.txt 并且程序必须知道它存在的位置
    • @ElyMan 好的,那么您将必须实现 SimpleFileVisitor&lt;Path&gt; 并遍历文件树,直到找到任何等于 f1\\f2\\file.txt 的子路径...
    • @ElyMan 我提供了一个例子,请看一下。
    • 感谢您的努力,但这是我的问题,我不知道 c:/ 或 d:/ 下是否有此“Files.walkFileTree(Paths.get("C:\\\\ "), pf);"如果我正在搜索的文件位于 z:/ 下,则永远不会工作
    • @ElyMan 好的,然后检查我对答案中底部示例的编辑,它现在检查所有可用的驱动器。
    猜你喜欢
    • 2011-07-09
    • 2011-01-26
    • 2011-09-17
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2016-11-19
    • 2010-09-18
    • 2010-12-17
    相关资源
    最近更新 更多