In an interview this is the question that is asked:
You have to write a program that take a directory name (e.g. D:\XYZ)
and a regular expression (e.g. “Olivea“) as an argument. And it will
list down all the files in the given directory with the name matched
with the regular expression.
I have made a simple program from this:
package temp;
import java.io.File;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FileSearch1 {
static ArrayList l = new ArrayList();
public static void main(String[] args) {
String folderName = "D:\\"; // the folder path in which you want to
// search
String strPattern = "Olivea"; // Pattern what you want to search
final boolean searchinFile = true; // if you want to search in file keep
// it true for folder search keep it
// false
File f = new File("D:\\");
Pattern pattern1 = Pattern.compile(strPattern);
sunny(f, pattern1, searchinFile);
}
public static void sunny(File f, Pattern pattern1,
final boolean searchinFileOnly) {
File[] f1 = f.listFiles();
if (f1 == null)
return;
int k = f1.length;
// System.out.println(k);
int i = 0;
while (i < k) {
File f2 = f1[i];
if (f2.isDirectory() && !searchinFileOnly) {
Matcher match1 = pattern1.matcher(f2.getName());
while (match1.find()) {
l.add("");
System.out.println(f2.getName());
}
} else if (f2.isFile() && searchinFileOnly) {
Matcher match1 = pattern1.matcher(f2.getName());
while (match1.find()) {
l.add("");
System.out.println(f2.getName());
}
}
sunny(f2, pattern1, searchinFileOnly);
i++;
}
}
}
After the written test, the interviewer asked me that which design
pattern could you use in this. Would you please suggest me the various
design patterns that we can implement in this code.?
Please help me how to apply composite and iterator pattern in this? Help will really be appreciated
Ignoring the fact that you have missed the No.1 Golden Rule of coding, namely that everything should be named correctly, you could use the Iterator and Composite patterns.
Composite would allow files and directories to be treated similarly.
Iterator is used to traverse a container and access the container’s elements. The iterator pattern decouples algorithms from containers.