1 Attachment(s)
Getting folder path - recursion
In a random set of nested folders and files, I need to get all folder paths where a particular child folder' name is say "x".
For example, in following structure, I need the program to return back only a\c\e\x
Attachment 1247
Please see that there can be any level of nesting and any folder structure. Thanks for help.
Re: Getting folder path - recursion
The File class has methods that will help you with this. What have you tried so far?
Do you have any specific questions about your program?
Re: Getting folder path - recursion
Quote:
Originally Posted by
Norm
The File class has methods that will help you with this. What have you tried so far?
Do you have any specific questions about your program?
I have been able to write a basic program to achieve what I wanted. However, it fails when in my previous diagram there is a directory 'dir x' under 'dir d'. So the program returns a\c\e\x and d\x. Can you help make that fix?
public class Zombie {
String folderName= new String();
ArrayList folderList= new ArrayList();
public static void main(String[] args) {
String path;
try {
path = new java.io.File(".").getCanonicalPath();
Zombie zombie= new Zombie();
getFilePaths(new File(path).listFiles(), zombie);
Iterator itr = zombie.folderList.iterator();
while (itr.hasNext())
System.out.println(itr.next());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void getFilePaths(File[] fileList, Zombie zombie) {
for (int i=0; i<fileList.length; i++) {
File file= fileList[i];
if (file.isDirectory()) {
if (containsDesiredFolder(file)) {
zombie.folderList.add(zombie.folderName+ "\\" + file.getName());
zombie.folderName="";
} else {
if (containsFoldersNotFiles(file)) {
zombie.folderName= zombie.folderName + "\\" + file.getName();
getFilePaths(file.listFiles(), zombie);
}
}
}
}
}
public static boolean containsFoldersNotFiles(File file) {
boolean flag = false;
if (file.isFile()) return false;
File[] dummyList = file.listFiles();
//no file or folder present
if (dummyList == null)
return flag;
for (int i = 0; i < dummyList.length; i++) {
File dummyFile = dummyList[i];
if (dummyFile.isDirectory() ) {
return true;
}
}
return flag;
}
public static boolean containsDesiredFolder(File file) {
boolean flag = false;
if (file.isFile()) return false;
File[] dummyList = file.listFiles();
if (dummyList == null)
return flag;
for (int i = 0; i < dummyList.length; i++) {
File dummyFile = dummyList[i];
if (dummyFile.isDirectory() && dummyFile.getName().equals("en_US")) {
flag = true;
}
}
return flag;
}
}
Re: Getting folder path - recursion
Please Edit your post and wrap your code with[code=java]<YOUR CODE HERE>[/code] to get highlighting
Post the program's output and explain what is wrong with it and show what you want it to be.