Search code examples
javafilerecursiontraversaldelete-file

Recursively Deleting a Directory


I have this section of code:

public static void delete(File f) throws IOException 
    {
        if (f.isDirectory()) 
        {
            for (File c : f.listFiles())
            {
                delete(c);
            }
        }
        else if (!f.delete())
        {
             throw new FileNotFoundException("Failed to delete file: " + f);
        }
    }   



 public static void traverseDelete(File directory) throws FileNotFoundException, InterruptedException
    {
        //Get all files in directory
        File[] files = directory.listFiles();
        for (File file : files)
        {
            if (file.getName().equalsIgnoreCase("word"))
            {
                boolean containsMedia = false;

                File[] filesInWordFolder = file.listFiles();

                for ( File file2 : filesInWordFolder ) 
                {
                    if ( file2.getName().contains("media"))
                    {
                        containsMedia = true;
                        break;
                    }
                }

                if (containsMedia == false)
                {
                    try 
                    {
                        delete(file.getParentFile());
                    } 
                    catch (IOException e) 
                    {
                        e.printStackTrace();
                    }
                }
            }
            else if (file.isDirectory())
            {
                traverseDelete(file);
            }
        }
    }

Sorry for the lack of commenting, but it's pretty self-explanatory, I think. Essentially what the code is supposed to do is traverses a set of files in a given directory, if it encounters a directory named "word", then it should list out the contents of word, and then if a directory called "media" does NOT exist, recursively delete everything within the parent directory of "word" down.

My main concern comes from this conditional:

if(!filesInWordFolder.toString().contains("media"))

Is that the correct way to say if the files in that array does not contain an instance of "image", go ahead and delete?


Solution

  • That won't work.

    File[] filesInWordFolder = file.listFiles();
    
    if(!filesInWordFolder.toString().contains("media"))
    

    will give you a string representation of a File array -- which will typically have a reference.

    You have to iterate through the files to find out if there's any in there that contain the word media.

    boolean containsMedia = false;
    
    for ( File file : filesInWordFolder ) {
    
    if ( file.getName().contains("media") ){
     containsMedia = true;
    break;
    }
    
    // now check your boolean
    if ( !containsMedia ) {