title: Using stack to make file/directory tree in Java
body: <p>I need to return or print a file/directory tree using stack data structure. For example:</p>
  
  <pre><code>Folder1
      Folder1.1
          File1.1.1
      Folder1.2
  Folder2
      File2.1
      File2.2
  ...
  </code></pre>
  
  <p>My code so far:</p>
  
  <pre><code>public static void filetree(File mainfolder, int indent){
  
      Stack&lt;String&gt; filesanddirectories = new Stack&lt;&gt;();
  
          for (File file : mainfolder.listFiles()){
              if (file.isDirectory()){
                  filesanddirectories.push(file.getName());
                  filetree(file, 0);
              }
              else if (file.isFile()){
                  filesanddirectories.push(file.getName());
              }
          }
  
      for (int i = 0; i &lt; filesanddirectories.size(); i++){
          System.out.println(filesanddirectories.pop());
      }
  }
  </code></pre>
  
  <p>This code prints folders and files but with no indention, backwards and not exactly in the right order.</p>
  
  <p>Could someone explain the logic of how it should work?</p>
  
  <p>EDIT: Found a solution using recursion and stack (although stack seems to be unnecessary)</p>