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

Tom*_*sky 35 java path

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

我有一个从文件A的目录文件B的相对路径.该路径可能并将使用".."以任意复杂的方式上升目录结构.

例A:

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

例B:

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

如何组合这两个以获得文件B 的最简单的绝对路径?

Fab*_*eeg 46

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

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
Run Code Online (Sandbox Code Playgroud)

  • @Tom:在这种情况下,使用`getCanonicalPath()`代替`getAbsolutePath()`可能就是你要找的东西. (9认同)

onl*_*man 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();
Run Code Online (Sandbox Code Playgroud)


rss*_*v10 11

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

  • `FileSystems.getDefault()`获取默认文件系统。对于此文件系统,将“ mayBeRelativePath”字符串转换为“ Path”对象。`normalize()`,即从路径的任何部分中删除`../ abc /../`之类的构造。如果还不是绝对值,则转换“ toAbsolutePath()”,并以字符串形式获取路径。 (3认同)

U.S*_*wap 5

从你的问题来看,如果我能做对,你正在寻找从相对路径获得绝对路径,那么你可以执行以下操作。

File b = new File("../some/relative/path");
String absolute = b.getCanonicalPath(); // may throw IOException
Run Code Online (Sandbox Code Playgroud)

或速记符号可以是,

String absolute = new File("../some/relative/path").getCanonicalPath();
Run Code Online (Sandbox Code Playgroud)