title: Find the deepest file/directory in the tree, Java
body: <p>I have a directory (<code>basedir3645</code>) containing a lot of nested directories and files (almost 40 000). Each nested directory may contain a few files and directories. The problem is to find the deepest file or directory (the method must return the nesting level of the deepest item and its name/path.</p>
  
  <pre><code>import java.io.File;
  
  public class Main {
  
      public static void main(String[] args) {
          String pathToDir = "D:\\Dropbox\\java\\tasks\\basedir3645";
          File baseDir = new File(pathToDir);
          System.out.println(findDeepestItem(baseDir));   
      }
  
      static public String findDeepestItem(File folder) {
          int currentLevel = 0;
          int deepestLevel = 0;
          String deepestItem = "";
          String result = "";
          File[] folderEntries = folder.listFiles();
          for (File entry : folderEntries) {
              currentLevel = countMatches(entry.getPath(), "\\");
              if (entry.isDirectory()) {
                  findDeepestItem(entry);
                  if (deepestLevel &lt; currentLevel) {
                      deepestLevel = currentLevel;
                      deepestItem = entry.getPath();
                  }
                  continue;
              } else {
                  if (deepestLevel &lt; currentLevel) {
                      deepestLevel = currentLevel;
                      deepestItem = entry.getPath();
                  }
              }
          }
          result = String.valueOf(deepestLevel) + " " + deepestItem;
          return result;
      }
  
      private static int countMatches(String path, String string) {
          int number = 0;
          String[] array = path.split("");
          for (int i = 0; i &lt; path.length(); i++) {
              if (string.contentEquals(array[i])) {
                  number++;
              }
          }
          return number;
      }
  }
  </code></pre>
  
  <p>Here I determine the nesting level of current item (file or directory) by counting the number of <code>\</code> occurencies in item <code>getPath()</code>.</p>
  
  <p>The program passes through all the element in tree (I've checked it, using <code>System.out.println("entry.getPath()");</code> in loop, but it cannot count he deepest nesting level.</p>