2017-04-23 98 views
0

请学习如何遍历一个没有递归的文件树/目录以及使用Java的堆栈。遍历一个没有递归和堆栈的文件树Java

public void traverse(Path path) 
throws IOException 
{ 
    Stack<Stream<Path>> st = new Stack<>(); 
    st.add(Files.list(path)); 
    for(Iterator<Path> it = st.peek().iterator(); it.hasNext();) 
    { 
     Path temp = it.next(); 
     final BasicFileAttributes fa = Files.readAttributes(temp, BasicFileAttributes.class); 
     if(fa.isDirectory()) 
     { 
      //list all the directory contents 
      st.push(Files.list(temp)); 
     } 
     else if(fa.isRegularFile()) 
     { 
     } 
     else if(fa.isSymbolicLink()) {} //symbolic link 
     else if(fa.isOther()) {} //other 
     else {} 
    } 
} 

谢谢!

回答

0

基本上你有一个路径树。像其他树一样遍历它。 他们提供了一个很好的例子,用于迭代,栈协助,有序,遍历二叉树here

尝试扩展。

所有堆栈都会为您提供一些“内存”,以便您可以在当前分支未能找到所需内容时返回树状结构。