Showing posts with label recursion. Show all posts
Showing posts with label recursion. Show all posts

Tuesday, December 16, 2014

Recursively listing directories

Note that this code is OS Agnostic (just because I am using File.separator instead of "//"), it has been tested on windows as well as Linux. Compile it as JAR and provide the directory name to iterate as sys.argv[0] and filename to store all the listing as sys.argv[1] . If using eclipse, refer to my previous post on how to provide the arguments in eclipse to a program -- it is very simple, just go to run configuration and you will find "arguments" there only.

This will list complete directory structure in my centos machine:
java -jar readDir2.jar / allFiles.txt


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

class dirTraversal{

public void traverseDir(String parentDir, String filename) throws IOException
{

File f = new File(parentDir);
FileWriter filewriter = new FileWriter(filename);
try {
listDir(f,filewriter);
filewriter.flush();
filewriter.close();
} catch (IOException e) {e.printStackTrace();}

}


private void listDir(File dirObject, FileWriter writer) throws IOException
{
String[] files;
files = dirObject.list();
for (String file:files)
{
File testDir = new File(dirObject + File.separator + file);
boolean isDir = testDir.isDirectory();
if(isDir == true)
{
writer.write("Directory Content for dir: " + testDir + "\n");
listDir(testDir,writer);
}
else
{
writer.write(file+ "\n");
}
}

}
}

public class readDir
{
public static void main(String[] args) throws IOException
{
dirTraversal obj = new dirTraversal();
obj.traverseDir(args[0], args[1]);

}
}