[英]Java get parent of parent
This is a very similar question to this one: How to get just the parent directory name of a specific file 这是一个非常类似的问题: 如何只获取特定文件的父目录名称
But there he wanted to get just the closest Parent directory, what I want is to be able to select other "Parents" such as: 但是在那里他想得到最近的父目录,我想要的是能够选择其他“父母”,例如:
bbb or ccc (considering the same example on the mentioned question) bbb或ccc (考虑到上述问题的相同例子)
File file = new File("C:/aaa/bbb/ccc/ddd/test.java"); 文件文件=新文件(“C:/aaa/bbb/ccc/ddd/test.java”);
I tried file.getParent().getParent();
我试过file.getParent().getParent();
which didn't work. 这没用。
Note: if possible I don't want to use regex on the path. 注意:如果可能,我不想在路径上使用正则表达式。
getParent()
returns a String
- you can't call getParent()
on a String
. getParent()
返回一个String
- 你不能在String
上调用getParent()
。
Instead, you want getParentFile()
: 相反,你想要getParentFile()
:
File grandparent = file.getParentFile().getParentFile();
getParent()
returns a String; getParent()
返回一个String; getParent()
returns a File; getParent()
返回一个File; eg: 例如:
Boolean fileNameChangedCheck = file.renameTo(
new File(filePath.getParentFile(), "changedFileName"));
Here filePath.getParentFile()
can't be replaced by filePath.getParent()
; 这里filePath.getParentFile()
不能被filePath.getParent()
替换;
There are more in JAVA API; JAVA API还有更多内容;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.