Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 314
Mansueli Avatar asked Dec 20 '22 14:12

Mansueli


1 Answers

getParent() returns a String - you can't call getParent() on a String.

Instead, you want getParentFile():

File grandparent = file.getParentFile().getParentFile();
like image 88
Jon Skeet Avatar answered Dec 29 '22 10:12

Jon Skeet