Traversing directories without using recursion?

后端 未结 8 1947
无人及你
无人及你 2021-01-18 06:46

The Problem I need to write a simple software that, giving certain constraints, appends to a list a series of files. The user could choose between

相关标签:
8条回答
  • 2021-01-18 07:27

    If you choose to use recursion, I found an example that may be close to the one you are currently using as to eliminate any ambiguity .

    // 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]));
            }
        }
    }
    

    This is a very simple example, the process() can be where you do your handling or operations on the directory.

    0 讨论(0)
  • 2021-01-18 07:30

    I am a real novice, but after working for a week on this problem... I have a clean solution... thanks for all the help from PATRY and etbal.

    public class Recur {
        // Process only directories under dir
    
    File dir;
    static DirectoryComponent allDirectory;
    
        public Recur(File dir, DirectoryComponent allDirectory) {
        // TODO Auto-generated constructor stub
            this.dir = dir;
    }
    
        public static DirectoryComponent Recur(File dir, DirectoryComponent allDirectory) {
            String file;
            String path;
    
             File firstDir = new File(dir.getPath());
             file = firstDir.getName();
             path = firstDir.getPath();
    
            if (dir.isDirectory()) {
    
                file = firstDir.getName();
                path = firstDir.getPath();
                DirectoryComponent directory = new Directory(file, path);
                allDirectory.add(directory);
    
                String [] subNote = dir.list();
                for(String filename : subNote){
                    File subNode = new File(firstDir, filename);
    
                    // store current child name
    
                        file = subNode.getName();
                        path = subNode.getPath();
                        directory.add(new FileItem(file,path));         
                }
    
                String[] children = dir.list();
                for (int i=0; i<children.length; i++) {
                    Recur(new File(dir, children[i]), allDirectory);
                }
            }
    
            return allDirectory;
        }
    }
    
    0 讨论(0)
提交回复
热议问题