Permalink
Browse files

Automatic removal of empty directories in a file storage (upon removal

of files).
  • Loading branch information...
1 parent a95b5e6 commit 6ff05e8e55b1a0c576a680d56bdd29859d36234a @cederberg committed Apr 7, 2012
@@ -1,6 +1,6 @@
/*
* RapidContext <http://www.rapidcontext.com/>
- * Copyright (c) 2007-2011 Per Cederberg. All rights reserved.
+ * Copyright (c) 2007-2012 Per Cederberg. All rights reserved.
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the BSD license.
@@ -240,6 +240,7 @@ public void remove(Path path) throws StorageException {
FileUtil.deleteFiles(file);
} else {
FileUtil.delete(file);
+ FileUtil.deleteEmptyDirs(baseDir);
}
} catch (IOException e) {
msg = "failed to remove " + file + ": " + e.getMessage();
@@ -1,6 +1,6 @@
/*
* RapidContext <http://www.rapidcontext.com/>
- * Copyright (c) 2007-2010 Per Cederberg. All rights reserved.
+ * Copyright (c) 2007-2012 Per Cederberg. All rights reserved.
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the BSD license.
@@ -157,6 +157,33 @@ public static void deleteFiles(File dir) throws IOException {
}
/**
+ * Deletes all empty directories in a directory, but leaves the
+ * directory itself unmodified. This method will remove any empty
+ * directories recursively, making it possible to remove a tree
+ * of empty directories.
+ *
+ * @param dir the directory to clean
+ *
+ * @throws IOException if some files couldn't be deleted
+ *
+ * @see #deleteFiles(File)
+ */
+ public static void deleteEmptyDirs(File dir) throws IOException {
+ File[] files = dir.listFiles();
+ if (files != null) {
+ for (int i = 0; i < files.length; i++) {
+ if (files[i].isDirectory()) {
+ deleteEmptyDirs(files[i]);
+ File[] subfiles = files[i].listFiles();
+ if (subfiles == null || subfiles.length == 0) {
+ delete(files[i]);
+ }
+ }
+ }
+ }
+ }
+
+ /**
* Creates a new temporary directory. If a temporary directory
* has been set, it will be used. Otherwise the default temporary
* directory will be used.

0 comments on commit 6ff05e8

Please sign in to comment.