代码之家  ›  专栏  ›  技术社区  ›  Tom Tresansky

将相对路径转换为绝对路径

  •  30
  • Tom Tresansky  · 技术社区  · 15 年前

    我有一个从文件a的目录到文件B的相对路径。此路径可能并将使用“.”以任意复杂的方式升级目录结构。

    • C:\projects\project1\module7\submodule5\fileA

    示例Bs:

    • ..\..\module3\submodule9\subsubmodule32\fileB
    • ..\submodule5\fileB
    • ..\..\module7\..\module4\submodule1\fileB
    • fileB

    如何将两者结合起来以获得 文件B的绝对路径?

    9 回复  |  直到 15 年前
        1
  •  52
  •   Fabian Steeg    15 年前

    如果我解决了你的问题,你可以这样做:

    File a = new File("/some/abs/path");
    File parentFolder = new File(a.getParent());
    File b = new File(parentFolder, "../some/relative/path");
    String absolute = b.getCanonicalPath(); // may throw IOException
    
        2
  •  21
  •   meyi    6 年前
    String absolutePath = FileSystems.getDefault().getPath(mayBeRelativePath).normalize().toAbsolutePath().toString();
    
        3
  •  15
  •   onlyhuman    10 年前

    您也可以使用 Path 接口:

    Path basePath = FileSystems.getDefault().getPath("C:\\projects\\project1\\module7\\submodule5\\fileA");
    Path resolvedPath = basePath.getParent().resolve("..\\..\\module3\\submodule9\\subsubmodule32\\fileB"); // use getParent() if basePath is a file (not a directory) 
    Path abolutePath = resolvedPath.normalize();
    
        4
  •  4
  •   U.Swap    7 年前

    从你的问题,如果我能得到它的权利,你正在寻找一个从相对路径的最佳路径,然后你可以做以下。

    File b = new File("../some/relative/path");
    String absolute = b.getCanonicalPath(); // may throw IOException
    

    或者简写符号可以是,

    String absolute = new File("../some/relative/path").getCanonicalPath();
    
        5
  •  3
  •   yegor256    12 年前
        6
  •  1
  •   Marcus Junius Brutus    9 年前

    比创建一个将相对路径转换为绝对路径的实用程序更好的方法是创建一个将传递给它的任何路径转换为绝对路径的实用程序,这样就不必在客户端进行检查。

    下面的代码在这两种情况下都适用,我使用了 String 在方法的签名处键入(参数和返回值):

    public static String toAbsolutePath(String maybeRelative) {
        Path path = Paths.get(maybeRelative);
        Path effectivePath = path;
        if (!path.isAbsolute()) {
            Path base = Paths.get("");
            effectivePath = base.resolve(path).toAbsolutePath();
        }
        return effectivePath.normalize().toString();
    }
    

    更改上述代码以公开 Path 方法签名上的类型很简单(实际上更容易),但我认为 字符串

        7
  •  0
  •   code_fish    12 年前

    下面是对我有用的示例代码。

     public String absolutePath(String relative, String absoluteTo)
        {       
            String[] absoluteDirectories = relative.split("\\\\");
            String[] relativeDirectories = absoluteTo.split("\\\\");
            int relativeLength = relativeDirectories.length;
            int absoluteLength = absoluteDirectories.length; 
            int lastCommonRoot = 0;
            int index;
            for (index = 0; index < relativeLength; index++)
                if (relativeDirectories[index].equals("..\\\\"))
                    lastCommonRoot = index;
                else
                    break;
            StringBuilder absolutePath = new StringBuilder();
            for (index = 0; index < absoluteLength - lastCommonRoot; index++)
            {  
                 if (absoluteDirectories[index].length() > 0) 
                     absolutePath.append(absoluteDirectories[index] + "\\\\");                          
            }
            for (index = lastCommonRoot; index < relativeLength  - lastCommonRoot; 
                                                                   index++)
            {  
                 if (relativeDirectories[index].length() > 0) 
                     absolutePath.append(relativeDirectories[index] + "\\\\");                          
            }
            return absolutePath.toString();              
        }
    

    public String relativePath(String absolute, String relativeTo) throws Exception
        {       
            String[] absoluteDirectories = absolute.split("\\\\");
            String[] relativeDirectories = relativeTo.split("\\\\");
            int length = absoluteDirectories.length < relativeDirectories.length ?
                            absoluteDirectories.length : relativeDirectories.length;
            int lastCommonRoot = -1;
            int index;
            for (index = 0; index < length; index++)
                if (absoluteDirectories[index].equals(relativeDirectories[index]))
                    lastCommonRoot = index;
                else
                    break;
            if (lastCommonRoot > -1){
                StringBuilder relativePath = new StringBuilder();
                for (index = lastCommonRoot + 1; index <absoluteDirectories.length;
                                                                             index++)
                    if (absoluteDirectories[index].length() > 0)
                        relativePath.append("..\\\\");
                for (index = lastCommonRoot + 1; index <relativeDirectories.length-1;
                                                                             index++)
                    relativePath.append(relativeDirectories[index] + "\\\\");
                relativePath.append(relativeDirectories[relativeDirectories.length - 1]);
                return relativePath.toString();         
            }
            else{
                throw new Exception("No common root found between working direcotry and filename");
            }            
        }
    
        8
  •  0
  •   simeg user3889184    8 年前

    我知道这不是最好的解决方案,但是你不能把fileA的路径的子串从0到 lastIndexOf("\")

    示例A:

    • C:\projects\project1\module7\submodule5\fileA

    示例Bs:

    • ..\..\module3\submodule9\subsubmodule32\fileB

    C:\projects\project1\module7\submodule5\..\..\module3\submodule9\subsubmodule32\fileB

    如果你不想 .. 在那里,这将需要更长的时间,但我建议通过这条路的时间 fileB 并将子串从0一直取到 \ . 然后检查子字符串。如果是的话 .. fileA's 路径自 lastIndexOf(\) 到长度。然后重复。这样就可以删除不需要的文件夹和 ..s

    所以:

    示例Bs:

    • ..\..\module3\submodule9\subsubmodule32\fileB

      --&燃气轮机; C:\projects\project1\module3\submodule9\subsubmodule32\fileB

        9
  •  -3
  •   simeg user3889184    8 年前

    完整Java路径的Windows路径。

    String winPath = downloadPath+"\\"+dir_contents[i].getName();
    String absPath = winPath.replace("\\","\\\\");
    
    推荐文章