Difference between revisions of "Traverse the files and directories under a directory"

From CodeCodex

(Ruby)
(ruby)
Line 2: Line 2:
 
===Java===
 
===Java===
 
This example implements methods that recursively visits all files and directories under a directory.
 
This example implements methods that recursively visits all files and directories under a directory.
<pre>
+
<pre class="java">
 
     // Process all files and directories under dir
 
     // Process all files and directories under dir
 
     public static void visitAllDirsAndFiles(File dir) {
 
     public static void visitAllDirsAndFiles(File dir) {
Line 42: Line 42:
  
 
===Ruby===
 
===Ruby===
<pre>
+
<pre class="ruby">
def list_dir(path='.')
+
def process(path)
 +
  puts path
 +
end
 +
 
 +
def traverse(path='.')
 
   Dir.entries(path).each do |name|
 
   Dir.entries(path).each do |name|
     next  if name[0,1] == '.'
+
     next  if name == '.' or name == '..'
 
     path2 = path + '/' + name
 
     path2 = path + '/' + name
     puts path2
+
     process(path2)
     if File.ftype(path2) == "directory"
+
     traverse(path2)  if File.ftype(path2) == "directory"
      list_dir(path2)
+
    end
+
 
   end
 
   end
 
end
 
end
  
list_dir("/work")
+
traverse("/work/backup")
 
</pre>
 
</pre>
  

Revision as of 18:02, 15 January 2011

Implementations

Java

This example implements methods that recursively visits all files and directories under a directory.

    // Process all files and directories under dir
    public static void visitAllDirsAndFiles(File dir) {
        process(dir);
    
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllDirsAndFiles(new File(dir, children[i]));
            }
        }
    }
    
    // Process only directories under dir
    public static void visitAllDirs(File dir) {
        if (dir.isDirectory()) {
            process(dir);
    
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllDirs(new File(dir, children[i]));
            }
        }
    }
    
    // Process only files under dir
    public static void visitAllFiles(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllFiles(new File(dir, children[i]));
            }
        } else {
            process(dir);
        }
    }

Ruby

def process(path)
  puts path
end

def traverse(path='.')
  Dir.entries(path).each do |name|
    next  if name == '.' or name == '..'
    path2 = path + '/' + name
    process(path2)
    traverse(path2)  if File.ftype(path2) == "directory"
  end
end

traverse("/work/backup")