0

How should I effectively check for the availability of particular folder(myfolder) recursively and if available, then create a tmp directory parallel to it Example:

#ls -l
--parent folder
  --projects
    -- sub folders (further depth is possible)
      -- myfolder
      -- tmp

I'm from python background and yet to get used to java. Below is what I could come up with.

import java.io.File;
 
class Main
{
    public static void main(String[] args)
    {  
        String currentDir = System.getProperty("user.dir");
        String projectDir = currentDir + "/projects"; // under this I have to search the for the `myfolder` recursively.
        File file = new File(projectDir);
 
        if (file.isDirectory()) {
            new File("tmp").mkdirs();
          }
        else {
            System.out.println("Directory doesn't exist!!");
        }
    }

note: I use java 8

Rafa S
  • 45
  • 5
  • You haven't implemented any recursion? – Lino Feb 07 '22 at 09:29
  • @Lino : argh, quite couldn't able to make out the exact syntax, my bad :( – Rafa S Feb 07 '22 at 09:31
  • I suggest you to follow some simple java tutorials. Recursion behaves the same as in probably every other language. You just call the method from inside its own body... – Lino Feb 07 '22 at 09:34
  • Does this answer your question? [Recursively list files in Java](https://stackoverflow.com/questions/2056221/recursively-list-files-in-java) – Joeblade Feb 07 '22 at 09:39

1 Answers1

0

Below is a method that recursively searches through all the sub-directories that might be contained within the provided local directory path for a specific directory (folder) name. When the first instance of that directory name is found the search halts and the full path to that directory is returned.

From that point, the returned path string should be parsed to get the parent path. Something like that could be done something like this:

String foundFolderParentPath = foundDirectory.substring(0, 
                                  foundDirectory.lastIndexOf(File.separator));

Now you would want to check and see if the tmp directory already exists there. Maybe you don't need to create it or, you may want to carry out some other action based on that fact:

if (new File(foundFolderParentPath + File.separator + "tmp").exists()) {
    // tmp already exists...Do whatever...
}
else {
    // Otherwise Create the tmp directory...
    new File(foundFolderParentPath + File.separator + "tmp").mkdir();
}

Here is the recursive findDirectory() method:

/**
 * This method recursively searches through all sub-directories beginning 
 * from the supplied searchStartPath until the supplied folder to find is 
 * found.<br>
 * 
 * @param searchStartPath (String) The full path to start the search from.<br>
 * 
 * @param folderToSearchFor (String) The directory (folder) or sub-directory 
 * (sub-folder) name to search for. Just a single name should be supplied, not multiple directory names..<br>
 * 
 * @return (String) If the search is successful then the full path to that 
 * found folder is returned. If the search was unsuccessful then Null String
 * (""), an empty string is returned.
 */
public static String findDirectory(String searchStartPath, String folderToSearchFor) {
    String foundPath = "";
    File[] folders = new File(searchStartPath).listFiles(File::isDirectory);
    if (folders.length == 0) {
        return "";
    }
    String tmp;
    for (int i = 0; i < folders.length; i++) {
        String currentPath = folders[i].getAbsolutePath();
        if (currentPath.equals(folderToSearchFor) || 
                    currentPath.substring(currentPath.lastIndexOf(File.separator) + 1)
                                      .equals(folderToSearchFor)) {
             foundPath = currentPath;
             break;
        }
        tmp = "";
        // The recursive call...
        tmp = findDirectory(folders[i].getAbsolutePath(), folderToSearchFor);
        if (!tmp.isEmpty()) {
            // Directory is found...
            foundPath = tmp;
            break; // Get out of loop. It's No longer needed.
        }
    }
    return foundPath;
}

How you might use this method:

String currentDir = System.getProperty("user.dir");
String projectDir = currentDir + "/Projects"; // under this I have to search the for the `myfolder` recursively.
String searchForDirectory =  "mySpecialFolder";
String foundDirectory = findDirectory(currentDir, searchForDirectory);
    
if (foundDirectory.isEmpty()) {
    System.out.println("The folder to find (" + searchForDirectory 
                     + ") could not be found!");
}
else {
    System.out.println("The ' " + searchForDirectory + 
                       "' Folder is found at: --> " + foundDirectory);
    /* Create the 'tmp' folder within the same parent folder where 
       mySpecialFolder resides in.                      */
    String foundFolderParentPath = foundDirectory.substring(0, 
                            foundDirectory.lastIndexOf(File.separator));
        
    // Is there a 'tmp' folder already there?
    if (new File(foundFolderParentPath + File.separator + "tmp").exists()) {
        // Yes there is..
        System.out.println("\nThere is no need to create the 'tmp' folder! It already"
                    + "exists within the\nparent path of: --> " + foundFolderParentPath);
    }
    else {    
        // No here isn't so create it...
        new File(foundFolderParentPath + File.separator + "tmp").mkdir();
        System.out.println("The 'tmp' folder was created within the parent path indicated below:");
        System.out.println(foundFolderParentPath);
        System.out.println();
    }
        
    // Display a File-Chooser to prove it just for the heck of it.
    javax.swing.JFileChooser fc = new javax.swing.JFileChooser(foundFolderParentPath);
    fc.showDialog(null, "Just A Test");
}
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22