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

时间:2010-07-08 15:01:37

标签: java path

我有一个文件A的绝对路径。

我有一个文件A目录中文件B的相对路径。这条路径可能并将使用“..”以任意复杂的方式上传目录结构。

示例A:

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

示例Bs:

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

如何将两者合并以获得文件B的最简单的绝对路径?

9 个答案:

答案 0 :(得分:43)

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

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

答案 1 :(得分:14)

Java 7 中,您还可以使用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();

答案 2 :(得分:9)

String absolutePath = FileSystems.getDefault()。getPath(mayBeRelativePath).normalize()。toAbsolutePath()。toString();

答案 3 :(得分:3)

答案 4 :(得分:2)

  

从你的问题来看,如果我能做对,那你就是想从相对路径获得绝对的路径,那么你就可以做到。

plyr

或简写符号可以是,

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

答案 5 :(得分:1)

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

以下代码在两种情况下都适用于我,并且我在方法的签名处使用了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类型是微不足道的(实际上更容易),但我认为在签名上使用String可以提供更大的灵活性。

答案 6 :(得分:0)

我知道这不是最好的解决方案,但是你不能只将fileA的路径的子字符串从0组合到lastIndexOf("\")的fileB的路径。

示例A:

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

示例Bs:

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

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

如果您不希望..在那里,则需要更长时间,但我建议您浏览fileB的路径并继续将子字符串从0转到{的第一个索引{1}}。然后检查子字符串。如果是\,则从那里删除子字符串,并将..路径中的子字符串从fileA's移除到长度。然后重复一遍这样您就可以删除不需要的文件夹和lastIndexOf(\)

所以:

示例A:

  • ..s

示例Bs:

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

    - > ..\..\module3\submodule9\subsubmodule32\fileB

答案 7 :(得分:0)

以下是适用于我的示例代码。

 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 :(得分:-3)

完整Java路径的Windows路径。

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