Converting Relative Paths to Absolute Paths

前端 未结 9 1244
北荒
北荒 2020-12-05 04:14

I have an absolute path to file A.

I have a relative path to file B from file A\'s directory. This path may and will use \"..\" to go up the directory structure in

相关标签:
9条回答
  • 2020-12-05 05:05

    If I get your problem right, you could do something like this:

    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
    
    0 讨论(0)
  • 2020-12-05 05:11

    I know it isn't the best solution but can't you just combine the substring of fileA's path from 0 to the lastIndexOf("\") with fileB's path.

    Example A:

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

    Example Bs:

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

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

    If you don't want the .. in there then, it would take longer, but I recommend going through the path for fileB and keep taking the substring from 0 to the first index of \. Then check the substring. If it is .. then remove the substring from there and remove the substring from fileA's path from lastIndexOf(\) to length. Then repeat. That way you are removing the folders you don't need and the ..s.

    So :

    Example A:

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

    Example Bs:

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

      --> C:\projects\project1\module3\submodule9\subsubmodule32\fileB

    0 讨论(0)
  • 2020-12-05 05:15

    Windows path to full Java path.

    String winPath = downloadPath+"\\"+dir_contents[i].getName();
    String absPath = winPath.replace("\\","\\\\");
    
    0 讨论(0)
提交回复
热议问题