ProjectFilesPrinter

本文介绍了一个使用Java编写的程序,该程序可以递归地遍历指定目录下的所有文件和子目录,并按照目录层级输出文件路径。示例中演示了如何从Spring框架源代码的根目录开始遍历,展示其内部的包和文件结构。
import java.io.File;

/**  
 * @author Dao
 *   
 */
public class ProjectFilesPrinter
{
  private static int packageLevel = 0;
  private static int packageNumber = 0;
  /**  
   * @param args  
   */
  public static void main(String[] args)
  {
    String packageBasePath = "G:\\spring\\spring-framework-2.5\\src\\main\\java\\org";
    
    File file = new File(packageBasePath);
    
    showPackage(file, "");
  }
  
  private static void showPackage(File file, String basePath)
  {
    packageLevel++;
    
    String name = file.getName();
    
    if (file.isDirectory())
    {
      packageNumber++;
      
      String packagePath = basePath + name;
      
      print("+ " + packagePath);
      
      File[] subFiles = file.listFiles();
      
      for (File subFile : subFiles)
      {
        showPackage(subFile, packagePath + ".");
      }
    }
    else
    {
      String fileName = basePath + name;
      
      print("- " + fileName);
    }
    
    packageLevel--;
  }
  
  private static void print(String message)
  {
    String space = "  ";
    
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < packageLevel; i++)
    {
      sb.append(space);
    }
    
    sb.append(message);
    
    System.out.println(sb.toString());
  }
}

 效果

  + org
    + org.springframework
      + org.springframework.aop
        - org.springframework.aop.Advisor.java
        - org.springframework.aop.AfterAdvice.java
        - org.springframework.aop.AfterReturningAdvice.java
        - org.springframework.aop.AopInvocationException.java
        + org.springframework.aop.aspectj
          - org.springframework.aop.aspectj.AbstractAspectJAdvice.java
          - org.springframework.aop.aspectj.AspectInstanceFactory.java
          - org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer.java
.........

.........

.........

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值