0

This method will delete any files and empty directories provided in the fileList. It seems to be working. I use recursion to delete the empty directories and i'm worried about cases that will create an infinite loop. Any thoughts or things to consider with this approach?

public static void deleteFilesAndEmptyDirs(List<File> fileList) {
            boolean result = true;
            List<File> returnList = new LinkedList<File>();
            for (File file : fileList) {
                result = file.delete();
                if(result == false && file.isDirectory()) {
                    returnList.add(file);
                }
            }

            if(returnList.size() >= 1) {
                deleteFilesAndEmptyDirs(returnList);
            }
        }
4

2 回答 2

1

In linux, you can create a recursive link between two directories.

E.g, I made these two dirs:

$ ls -Rla
.:
total 24
drwxr-xr-x   4 dave dave  4096 2012-04-09 17:26 .
drwxr-xr-x 111 dave dave 12288 2012-04-09 17:25 ..
drwxr-xr-x   2 dave dave  4096 2012-04-09 17:27 dir1
drwxr-xr-x   2 dave dave  4096 2012-04-09 17:27 dir2

./dir1:
total 8
drwxr-xr-x 2 dave dave 4096 2012-04-09 17:27 .
drwxr-xr-x 4 dave dave 4096 2012-04-09 17:26 ..
lrwxrwxrwx 1 dave dave    8 2012-04-09 17:27 dir2 -> ../dir2/

./dir2:
total 8
drwxr-xr-x 2 dave dave 4096 2012-04-09 17:27 .
drwxr-xr-x 4 dave dave 4096 2012-04-09 17:26 ..
lrwxrwxrwx 1 dave dave    8 2012-04-09 17:27 dir1 -> ../dir1/

then I can do this:

 $ cd dir1/dir2/dir1/dir2/dir1/dir2/dir1/

Which if not checked for would cause a stack overflow.

于 2012-04-09T16:29:19.670 回答
1

Your method will recurse infinitely if it encounters a non empty directory. You have to add the contents of the nonempty directory to the list of files to delete.

I believe (but have not tested) that the below code is robust to recursive symbolic links.

public static void deleteFilesAndEmptyDirs(List<File> fileList) {
            boolean result = true;
            List<File> returnList = new LinkedList<File>();
            for (File file : fileList) {
                result = file.delete();
                if(result == false && file.isDirectory()) {
                  for ( File f : file . listFiles ( ) ) {
                    returnList.add(f);
                  }
                  returnList . add ( file ) ;
                }
            }

            if(returnList.size() >= 1) {
                deleteFilesAndEmptyDirs(returnList);
            }
        }
于 2012-04-09T17:42:20.133 回答