-2

假设我们有:

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
4

6 回答 6

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
于 2013-08-01T18:36:50.823 回答
2

你可以这样做:

Path p1 = Paths.get("D:\\aaa\\bbb\\ccc");
Path p2 = p1.getParent();
....
于 2013-08-01T18:37:06.507 回答
1
File file = new File("D:\\aaa\\bbb\\ccc");
File parent = file.getParent();

System.out.println(parent);
于 2013-08-01T18:38:41.850 回答
1

尝试这个

  Path path = Paths.get("your path");
  Path parentPath = path.getParent();
于 2013-08-01T18:40:02.363 回答
1
File path = new File("D:\aaa\bbb\ccc");
path.getParentFile();  // Returns "D:\aaa\bbb\"
path.getParentFile().getParentFile();  // Returns D:\aaa\"
于 2013-08-01T18:41:08.523 回答
0
File parent = new File("D:\\aaa\\bbb\\ccc").getParent();
System.out.println(parent);
于 2013-08-01T18:38:31.703 回答