[英]Drive letter in subpaths of Path
请考虑以下代码:
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestPath {
public static void main(String[] args) {
String filename = "c:/manyOthers/dir1/dir2/dir3";
File f = new File(filename);
String absPathS = f.getAbsolutePath();
System.out.println(absPathS);
// now I try to add a timestamp between dir1 and dir2/dir3 in abstPathS
Path absPath = Paths.get(absPathS);
int n = absPath.getNameCount();
String timestamp = "20210308";
Path subpath = absPath.subpath(0, n-2);
Path outPath = Paths.get(subpath.toString(), timestamp, absPath.subpath(n-2, n).toString());
System.out.println("Timestamped: " + outPath);
}
}
output 是:
c:\manyOthers\dir1\dir2\dir3
Timestamped: manyOthers\dir1\20210308\dir2\dir3
基本上 - 在我的实际代码中 - 我收到文件夹的绝对路径,我需要插入一个名称对应于时间戳的子文件夹。 上面的代码只是一个示例,我在这里使用它是为了提供一个简单的运行示例; 在实际代码中,该路径包含更多子文件夹c:/folder1/folder2/.../dir1/dir2/dir3
,因此,如果您打算回答这个问题,请不要针对上面的特定代码定制解决方案。
在上面的代码中,我有绝对路径C:/manyOthers/dir1/dir2/dir3/
并且我需要在dir1
和dir2/dir3
之间插入一个时间戳。 但是,如您所见,问题在于最终的 output 丢失了驱动器号。
我在其他地方读到,在 Java 中,没有办法添加回File.getAbsolutePath()
c:/
,但是因为前缀c:\
例如:
File f = new File("any");
System.out.println(f.getAbsolutePath());
印刷:
C:\Users\user\workspace\project\any
如何在路径中保留/重新插入驱动器号?
问题是Path.subPath
总是返回一个相对路径。
但幸运的是,您的Path absPath
是绝对的,并且包含C:\
作为根。 所以你可以通过absPath.getRoot()
得到它。
有了这个,您可以从该根目录创建Path outPath
:
...
Path outPath = Paths.get(absPath.getRoot().toString(), subpath.toString(), timestamp, absPath.subpath(n-2, n).toString());
...
正如@user15244370 评论的那样,使用Path.resolve
而不使用Paths
和Path.toString
,整个事情可以做得更加优雅。
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestPath {
public static void main(String[] args) {
String filename = "c:/manyOthers/dir1/dir2/dir3";
Path absPath = Paths.get(filename);
System.out.println("Source path: " + absPath);
int n = absPath.getNameCount();
String timestamp = "20210308";
Path subpath = absPath.subpath(0, n-2);
Path outPath = absPath.getRoot().resolve(subpath).resolve(timestamp).resolve(absPath.subpath(n-2, n));
System.out.println("Timestamped: " + outPath);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.