import java.io.*;
import java.util.*;
public class SearchTest {
static Random seed = new Random();
static String[] fileNames;
static String target;
static long start;
public static void main(String[] args) {
String searchDir = ".";
File folder = new File(searchDir);
List<String> list = new ArrayList<String>();
collectFileNames(folder, list);
fileNames = list.toArray(new String[list.size()]);
int index = seed.nextInt(fileNames.length);
target = fileNames[index];
System.out.printf("target = %s at index = %d of %d files%n",
target, index, fileNames.length);
start = System.currentTimeMillis();
new Thread(forward).start();
new Thread(reverse).start();
}
private static void collectFileNames(File folder, List<String> list) {
folder.setReadOnly();
File[] files = folder.listFiles();
for(int j = 0; j < files.length; j++) {
list.add(files[j].getName());
if(files[j].isDirectory())
collectFileNames(files[j], list);
}
}
private static synchronized void post(int index, long end, String caller) {
long time = end - start;
System.out.printf("%s found %s at index %d in %d millis%n",
caller, target, index, time);
}
private static Runnable forward = new Runnable() {
public void run() {
for(int j = 0; j < fileNames.length; j++) {
if(fileNames[j].equals(target)) {
long end = System.currentTimeMillis();
post(j, end, "forward");
break;
}
}
}
};
private static Runnable reverse = new Runnable() {
public void run() {
for(int j = fileNames.length-1; j >= 0; j--) {
if(fileNames[j].equals(target)) {
long end = System.currentTimeMillis();
post(j, end, "reverse");
break;
}
}
}
};
}