2

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?

1
  • split the string on / and off you go. Commented Aug 18, 2015 at 19:22

2 Answers 2

1

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]); } } 
Sign up to request clarification or add additional context in comments.

9 Comments

i am calling a method with a string parameter like getParentPaths(String url)
@Faizahamed added method which uses String argument
wat is this Path? i am getting problem in compiling a class.
can we go bit logical like spiting and looping it and all.. instead of doing this?
@Faizahamed Path and Paths are classes added in Java 7. They ware part of new API placed in java.nio.file package, which is meant to replace old File class. Are you perhaps using Java 6 or earlier?
|
0

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.