简体   繁体   中英

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)

File file = new File("C:/aaa/bbb/ccc/ddd/test.java");

I tried 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 .

Instead, you want getParentFile() :

File grandparent = file.getParentFile().getParentFile();

getParent() returns a String; getParent() returns a File; eg:

Boolean fileNameChangedCheck = file.renameTo(
        new File(filePath.getParentFile(), "changedFileName"));

Here filePath.getParentFile() can't be replaced by filePath.getParent() ;

There are more in JAVA API;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM