Java: dangerous self-returning-recursive function by IOException?
Posted
by HH
on Stack Overflow
See other posts from Stack Overflow
or by HH
Published on 2010-04-12T16:00:25Z
Indexed on
2010/04/12
16:03 UTC
Read the original article
Hit count: 389
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.
.
HELLO
com
TOASHEOU
google
common
annotations
base
collect
internal
Give me an path.
IT WON'T FIND ME, SO IT RETURNS ITSELF due to Exception caught
Give me an path.
$ cat SubDirs.java
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();
}
}
© Stack Overflow or respective owner