Difference between revisions of "Delete a directory"

From CodeCodex

 
(Implementations)
 
(3 intermediate revisions by 3 users not shown)
Line 29: Line 29:
 
</pre>
 
</pre>
 
* Original Source: [http://javaalmanac.com/egs/java.io/pkg.html?l=rel#Files The Java Developers Almanac 1.4]
 
* Original Source: [http://javaalmanac.com/egs/java.io/pkg.html?l=rel#Files The Java Developers Almanac 1.4]
 +
 +
===Perl===
 +
<HIGHLIGHTSYNTAX language="perl">
 +
# empty dir:
 +
rmdir($ourdir);
 +
 +
# not-so-emtpy dir:
 +
use File::Path;
 +
rmtree($ourdir);
 +
</HIGHLIGHTSYNTAX>
 +
 +
===Python===
 +
<HIGHLIGHTSYNTAX language="python">
 +
# empty dir:
 +
import os
 +
os.rmdir(ourdir)
 +
 +
# not-so-emtpy dir:
 +
import shutil
 +
shutil.rmtree(ourdir)
 +
</HIGHLIGHTSYNTAX>
 +
 +
===Ruby===
 +
<pre>
 +
# empty dir:
 +
Dir.rmdir('ourdir')
 +
 +
# not-so-emtpy dir:
 +
FileUtils.remove_entry_secure('ourdir')
 +
</pre>
 +
 +
=== Tcl ===
 +
<pre class="tcl">
 +
file delete -force ourdir
 +
</pre>
 +
 
[[Category:Java]]
 
[[Category:Java]]
 +
[[Category:Perl]]
 +
[[Category:Python]]
 +
[[Category:Ruby]]
 +
[[Category:Tcl]]
 
[[Category:I/O]]
 
[[Category:I/O]]

Latest revision as of 20:17, 1 March 2011

Implementations[edit]

Java[edit]

    // Delete an empty directory
    boolean success = (new File("directoryName")).delete();
    if (!success) {
        // Deletion failed
    }

If the directory is not empty, it is necessary to first recursively delete all files and subdirectories in the directory. Here is a method that will delete a non-empty directory.

    // Deletes all files and subdirectories under dir.
    // Returns true if all deletions were successful.
    // If a deletion fails, the method stops attempting to delete and returns false.
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
    
        // The directory is now empty so delete it
        return dir.delete();
    }

Perl[edit]

<HIGHLIGHTSYNTAX language="perl">

  1. empty dir:

rmdir($ourdir);

  1. not-so-emtpy dir:

use File::Path; rmtree($ourdir); </HIGHLIGHTSYNTAX>

Python[edit]

<HIGHLIGHTSYNTAX language="python">

  1. empty dir:

import os os.rmdir(ourdir)

  1. not-so-emtpy dir:

import shutil shutil.rmtree(ourdir) </HIGHLIGHTSYNTAX>

Ruby[edit]

# empty dir:
Dir.rmdir('ourdir')

# not-so-emtpy dir:
FileUtils.remove_entry_secure('ourdir')

Tcl[edit]

file delete -force ourdir