代码改变世界

processing递归显示树的内容

2013-04-17 11:57  youxin  阅读(960)  评论(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();
}