假设我们有:
String path = "D:\aaa\bbb\ccc"
我想知道是否有一项功能可以快速修改path
:
D:\aaa\bbb\
或D:\aaa\
我尝试使用Paths但没有运气:
path = "D:\\aaa\\bbb\\ccc";
pathNew = java.nio.file.Paths.get(path).subpath(0,2).toString();
println "${pathNew}"
提供下一个控制台结果:
aaa\bbb
答案 0 :(得分:5)
你可以这样做:
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
答案 1 :(得分:2)
你可以这样做:
Path p1 = Paths.get("D:\\aaa\\bbb\\ccc");
Path p2 = p1.getParent();
....
答案 2 :(得分:1)
File file = new File("D:\\aaa\\bbb\\ccc");
File parent = file.getParent();
System.out.println(parent);
答案 3 :(得分:1)
试试这个
Path path = Paths.get("your path");
Path parentPath = path.getParent();
答案 4 :(得分:1)
File path = new File("D:\aaa\bbb\ccc");
path.getParentFile(); // Returns "D:\aaa\bbb\"
path.getParentFile().getParentFile(); // Returns D:\aaa\"
答案 5 :(得分:0)
File parent = new File("D:\\aaa\\bbb\\ccc").getParent();
System.out.println(parent);