Discuss / Java / 练习

练习

Topic source

NB

#1 Created at ... [Delete] [Delete and Lock User]
public class ExerciseDemo1 {

    static int depth = 0; 
   
     public static void main(String[] args) throws IOException {
        if (args.length == 0) {
            File currentDir = new File(".");            
            listDir(currentDir.getCanonicalFile());            
            return;        
        }

        String specifyDirStr = args[0];        
        File specifyDir = new File(specifyDirStr);        
        listDir(specifyDir.getCanonicalFile());    
    }

     static void listDir(File dir) {
        // TODO: 递归打印所有文件和子文件夹的内容        
        depth++;        
        File[] fs = dir.listFiles();        
        if (fs != null) {
             for (File f : fs) {
                printT(depth - 1);                
                if (f.isDirectory()) {
                    System.out.println(f.getName() + "/");                
                } else {
                    System.out.println(f.getName());                
                }
                listDir(f);            
             }
        
        }
        depth--;    
     }

     static void printT(int depth) {
        for (int i = depth; i > 0; i--) {
            System.out.print("\t");        
        }
     }
}

  • 1

Reply