4

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.

Community
  • 1
  • 1
Mansueli
  • 6,223
  • 8
  • 33
  • 57
  • 1
    Well did `file.getParent().getParent()` not work? What happened? (If you've got an idea of what to do, and you've tried it, you should always say what happened.) – Jon Skeet May 21 '14 at 18:32

2 Answers2

13

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

Instead, you want getParentFile():

File grandparent = file.getParentFile().getParentFile();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
-2

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;

Matt Ke
  • 3,599
  • 12
  • 30
  • 49
  • getParentFile() returns a File; – user10838135 Jan 08 '19 at 02:31
  • getParentFile() returns a File; – user10838135 Jan 08 '19 at 02:31
  • Hi, welcome to Stack Overflow. When answering a question with an accepted answer, please be sure to add some additional insight into why the response you're providing is somehow substantive and not simply echoing what's already been vetted by the original poster. In this case, you've duplicated the exact information already given by [@jon-skeet](https://stackoverflow.com/a/23791173/148680) – chb Jan 08 '19 at 03:13