I had very errorsome Exception handling with if-clauses. An exception occurs if not found path. An exception returns the function again. The function is recursive. Safe?
$ javac SubDirs.java $ java SubDirs Give me an path. . Dir1 Dir2 Give me an path. IT WON'T FIND ME, SO IT RETURNS ITSELF due to Exception caught Give me an path.
The code of Subdirs.java
looks like this:
import java.io.*;
import java.util.*;
public class SubDirs {
private List<File> getSubdirs(File file) throws IOException {
List<File> subdirs = Arrays.asList(file.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory();
}
}));
subdirs = new ArrayList<File>(subdirs);
List<File> deepSubdirs = new ArrayList<File>();
for(File subdir : subdirs) {
deepSubdirs.addAll(getSubdirs(subdir));
}
subdirs.addAll(deepSubdirs);
return subdirs;
}
public static void search() {
try{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
System.out.println("Give me an path.");
while ((s = in.readLine()) != null && s.length() != 0){
SubDirs dirs = new SubDirs();
List<File> subDirs = dirs.getSubdirs(new File(s));
for ( File f : subDirs ) {
System.out.println(f.getName());
}
System.out.println("Give me an path.");
}
}catch(Exception e){
// Simple but is it safe?
search();
}
}
public static void main(String[] args) throws IOException {
search();
}
}