Hello,
I have this code (pasted below) which is part of a program where a user is asked to type 'dir' or 'file' in the command prompt and if the user types 'dir' then only the directories of the folder are displayed while if the user types 'file', both the files and directories are displayed. There are 2 methods that handle the request.
My question is that although my program works, both the methods have almost same code. Can I get rid of one of the methods by passing an if statement? I am aware we can do that but my skills in
Java are not that advanced and I can't figure out how.
Shall be really grateful for help.
Ricky
=========================================
public void printContentsBoth(File folder){
indentLevel++;
File[] directorys = folder.listFiles(new IsDirectory());
for(int i=0; i < directorys.length; i++){
// code for getting the number of files and size of files
String pathOfDirectory = directorys[i].getPath();
File currentFolder = new File(pathOfDirectory);
File[] folderList = currentFolder.listFiles(new IsNotDirectory());
int numOfFiles = folderList.length;
for(int j = 0; j < numOfFiles; j++) {
fileSize += folderList[j].length();
}
// indent the name of directories and sub-directories
for(int indent = 0; indent < indentLevel; indent++) {
System.out.print(" ");
}
System.out.println(directorys[i].getName() + "(" + numOfFiles + ")" + "(" + fileSize + ")");
printContentsBoth(directorys[i]);
}
File[] files = folder.listFiles(new IsNotDirectory());
for(int i=0; i < files.length; i++){
for (int indent = 0; indent < indentLevel; indent++) {
System.out.print(" ");
}
System.out.println(files[i].getName());
}
indentLevel--;
}
/*
* This method prints the folders only in a given absolute path
*/
public void printContentsDir(File folder){
indentLevel++;
File[] directorys = folder.listFiles(new IsDirectory());
for(int i=0; i < directorys.length; i++){
// code for getting the number of files and size of files
String pathOfDirectory = directorys[i].getPath();
File currentFolder = new File(pathOfDirectory);
File[] folderList = currentFolder.listFiles(new IsNotDirectory());
int numOfFiles = folderList.length;
for(int j = 0; j < numOfFiles; j++) {
fileSize += folderList[j].length();
}
// indent the name of directories and sub-directories
for(int indent = 0; indent < indentLevel; indent++) {
System.out.print(" ");
}
System.out.println(directorys[i].getName() + "(" + numOfFiles + ")" + "(" + fileSize + ")");
printContentsDir(directorys[i]);
}
indentLevel--;
}
=======================================================
[ March 28, 2007: Message edited by: Ricky James ]