递归遍历目录下所有文件
递归遍历目录下所有文件
《数据结构与算法分析——Java语言描述》的一个算法伪代码,通过引入depth突出了文件的层次结构。
伪码:
	private void listAll(int depth){
		printName(depth); //Print the name of the object
		if(isDirectory())
			for each file c in this directory (for each child)
				c.listAll(depth + 1);
	}
	
	public void listAll(){
		listAll(0);
	}
实现:
package com.czf.inspirations;
import org.junit.Test;
import java.io.File;
public class PrintAllDir {
    @Test
    public void testPrintAllDir(){
        File file = new File("D:\\作业\\Java\\JDBC\\src");
        printAllDir(file, 0);
    }
    /**
     * 递归列出目录中所有文件的名字。
     * 输出格式将是:深度为di的文件将被di次跳格(tab)缩进后打印其名。
     * @param file
     * @param depth
     */
    public void printAllDir(File file, int depth){
        for (int i = 0; i < depth; i++) {
            System.out.print('\t');
        }
        System.out.println(file.getName());
        if(file.isDirectory()){
            for (File listFile : file.listFiles()) {
                printAllDir(listFile, depth + 1);
            }
        }
    }
}
输出:
src
	com
		czf
			bean
				Customer.java
				Order.java
			connection
				ConnectionTest.java
			inspirations
				PrintAllDir.java
			preparedstatement
				crud
					CustomerForQuery.java
					OrderForQuery.java
					PreparedStatementUpdateTest.java
			util
				JDBCUtils.java
	jdbc.properties
Process finished with exit code 0
                    
                
                
            
        
浙公网安备 33010602011771号