Empty directory: Difference between revisions
+Java 7 |
m →{{header|Java}}: before anyone asks |
||
Line 5: | Line 5: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|7+}} |
{{works with|Java|7+}} |
||
This method does not check that the path given is actually a directory. If a path to a normal file is given, it will throw a <code>NullPointerException</code>. |
This method does not check that the path given is actually a directory. If a path to a normal file is given, it will throw a <code>NullPointerException</code>. <code>File.listLess()</code> does not count the "." and ".." entries. |
||
<lang java5>import java.nio.file.Paths; |
<lang java5>import java.nio.file.Paths; |
||
//... other class code here |
//... other class code here |
||
Line 11: | Line 11: | ||
return Paths.get(dirName).toFile().listFiles().length == 0; |
return Paths.get(dirName).toFile().listFiles().length == 0; |
||
}</lang> |
}</lang> |
||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
{{works with|Ruby|1.8.7}} |
{{works with|Ruby|1.8.7}} |
Revision as of 06:02, 3 January 2012
Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.
” and almost every directory contains “..
” (except for a root directory); an empty directory contains no other entries.
Java
This method does not check that the path given is actually a directory. If a path to a normal file is given, it will throw a NullPointerException
. File.listLess()
does not count the "." and ".." entries.
<lang java5>import java.nio.file.Paths;
//... other class code here
public static boolean isEmptyDir(String dirName){
return Paths.get(dirName).toFile().listFiles().length == 0;
}</lang>
Ruby
<lang ruby># Checks if a directory is empty, but raises SystemCallError
- if _path_ is not a directory.
def empty_dir?(path)
not Dir.foreach(path).detect {|f| f != '.' and f != '..'}
end</lang>
If Ruby is older than 1.8.7, then Dir.foreach must take a block.
<lang ruby># Checks if a directory is empty, but raises SystemCallError
- if _path_ is not a directory.
def empty_dir?(path)
Dir.foreach(path) {|f| return false if f != '.' and f != '..' } return true
end</lang>
Tcl
<lang tcl>proc isEmptyDir {dir} {
# Get list of _all_ files in directory set filenames [glob -nocomplain -tails -directory $dir * .*] # Check whether list is empty (after filtering specials) expr {![llength [lsearch -all -not -regexp $filenames {^\.\.?$}]]}
}</lang>