Faiz ahamed
Faiz ahamed

Reputation: 41

get all the sub parent folders from given path in java

I am trying to print all parent folders from the path specified using Java.

For instance,I got this path

/root/p0/p1/p2/p3/report

Now my expected output is

/root/p0/p1/p2/p3

/root/p0/p1/p2

/root/p0/p1

/root/p0

/root

How can we do this in Java? Any pre-defined functions exist in Java or by looping it? How to loop this path and get the expected parent url's?

Upvotes: 2

Views: 1138

Answers (2)

Pshemo
Pshemo

Reputation: 124225

You could try using getParent form Path, or gerParentFile from File. Your code can look like:

public static void printParents(File f){
    while(f != null){
        f = f.getParentFile();
        if (f !=null && !f.getName().isEmpty()) 
            System.out.println(f);
    }
}
public static void printParents(String f){
    printParents(new File(f));
}

You can also use String methods like split to get all parts from this path. Then you can join parts you want like

public static void printParents(String path){
    String[] elements = path.split("(?<!^)/");
    StringBuilder sb = new StringBuilder(elements[0]);
    for (int i=1; i<elements.length; i++){
        System.out.println(sb);
        sb.append("/").append(elements[i]);
    }
}

Upvotes: 1

scott_lotus
scott_lotus

Reputation: 3275

Have you tried the getParent function:

public static String getParentName(File file) {
if(file == null || file.isDirectory()) {
        return null;
}
String parent = file.getParent();
parent = parent.substring(parent.lastIndexOf("\\") + 1, parent.length());
return parent;      
}

Upvotes: 0

Related Questions