我有一个文件A的绝对路径.
我有一个从文件A的目录文件B的相对路径.该路径可能并将使用".."以任意复杂的方式上升目录结构.
例A:
C:\projects\project1\module7\submodule5\fileA例B:
..\..\module3\submodule9\subsubmodule32\fileB..\submodule5\fileB..\..\module7\..\module4\submodule1\fileBfileB如何组合这两个以获得文件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)
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();
从你的问题来看,如果我能做对,你正在寻找从相对路径获得绝对路径,那么你可以执行以下操作。
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)
| 归档时间: |
|
| 查看次数: |
42902 次 |
| 最近记录: |