代码改变世界

processing递归显示树的内容

  youxin  阅读(970)  评论(0编辑  收藏  举报

下面的代码递归显示某一文件的内容,考虑了非常多的因素,代码比较细致。

Node类:

Node作为树结构中的基本元素,每个元素或者是文件或者是目录。

复制代码
import java.io.File;
class Node
{
  File file;
  Node[]  children;//子节点
  int childCount;
  
  Node(File file){
    this.file=file;
    if(file.isDirectory())
    {
      String[] contents=file.list();
      if(contents!=null)//有些文件不能访问,file.list返回null
      {
        contents=sort(contents);
      children=new Node[contents.length];
      for(int i=0;i<contents.length;i++)
      {
        if(contents[i].equals(".")||contents[i].equals(".."))
        {
          continue;
        }
        File childFile=new File(file,contents[i]);
        //skip any file that appears to be s symbolic link
        try{
          String absPath=childFile.getAbsolutePath();//将路径转为实际位置
          String canPath=childFile.getCanonicalPath();//返回路径名,但不能解析连接
          if(!absPath.equals(canPath))
          {
            continue;
          }
        }catch(IOException e){ }
        
        Node child=new Node(childFile);
        children[childCount++]=child;//为什么不用chidlren【i。因为unix 。 。。表示当前目录
        
      }
    }
    }//end if(content!=null)
  }
  
  void printList()
  {
    printList(0);
  }
  
  void printList(int depth)
  {
    //print spaces for each level of depth
    for(int i=0;i<depth;i++)
    {
      print("—");
    }
    println(file.getName());
    for(int i=0;i<childCount;i++)
    {
      children[i].printList(depth+1);
    }
  }
}
复制代码

setup

void setup()
{
  File rootFile=new File("C:\\jPaginate");
  Node rootNode=new Node(rootFile);
  rootNode.printList();
}

  

 

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2012-04-17 转:VS后缀名详解
2012-04-17 c++ pair类型
点击右上角即可分享
微信分享提示