2017-04-23 96 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

嘗試擴展。

所有堆棧都會爲您提供一些「內存」,以便您可以在當前分支未能找到所需內容時返回樹狀結構。