假设我们有:
String path = "D:\aaa\bbb\ccc"
我想知道是否有一个功能可以快速修改path
为:
D:\aaa\bbb\
或者D:\aaa\
我尝试使用没有运气的路径:
path = "D:\\aaa\\bbb\\ccc";
pathNew = java.nio.file.Paths.get(path).subpath(0,2).toString();
println "${pathNew}"
给出下一个控制台结果:
aaa\bbb
你可以做:
String path = "D:\\aaa\\bbb\\ccc";
File parent = new File(path).getParentFile();
System.out.println(parent);
String parentStr = new File(path).getParent();
System.out.println(parentStr);
印刷:
D:\aaa\bbb
D:\aaa\bbb
你可以这样做:
Path p1 = Paths.get("D:\\aaa\\bbb\\ccc");
Path p2 = p1.getParent();
....
File file = new File("D:\\aaa\\bbb\\ccc");
File parent = file.getParent();
System.out.println(parent);
尝试这个
Path path = Paths.get("your path");
Path parentPath = path.getParent();
File path = new File("D:\aaa\bbb\ccc");
path.getParentFile(); // Returns "D:\aaa\bbb\"
path.getParentFile().getParentFile(); // Returns D:\aaa\"
File parent = new File("D:\\aaa\\bbb\\ccc").getParent();
System.out.println(parent);