1

I have a directory named "madhura" and i am trying to delete it.Directory "madhura" contains another directory "anyname" and a text file."anyname " also contains a directory.There is no error given by the code i have written ,however nothing is deleted.

please help me with the issue

Code:

package testjava;

import java.io.File;
import java.io.IOException;

public class DeleteDirectory {
    public static void main(String args[])
    {
        File f = new File("C:\\madhura");
        try {
            deleteDirectory(f.list());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void deleteDirectory(String[] path) throws Exception
    {
        System.out.println("Inside delteDirectory");
        int i=0;
        int count = path.length;
        System.out.println(path.length);
        while(i<count)
        {
        File f = new File(path[i]);
        System.out.println("file "+f+" isdiretory "+f.isDirectory());
        if(f.isDirectory())
        {
            System.out.println("Inside f.isdirectory");
            deleteDirectory(f.list());
            f.delete();
        }
        else{

            System.out.println("deleting "+f);
            System.out.println(f.delete());

        }
        i++;
        }
    }
}

output:

Inside delteDirectory
2
file anyname isdiretory false
deleting anyname
false
file New Text Document.txt isdiretory false
deleting New Text Document.txt
false
  • U can use File.list() method to list all the filenames in a dir and then file.delete to delete the same. – Mogana May 19 '14 at 12:20

2 Answers2

1

From the documentation(Java API) I got the following :

public boolean delete()

Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.

Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

For further help you should use the java.nio.file.Files it has method walkFileTree and delete you can use these methods to delete all the files under a directory.

Bilbo Baggins
  • 2,899
  • 10
  • 52
  • 77
0

Try this one

File file = new File("C:\\Example");        
    String[] myFiles;      
        if(file.isDirectory()){  
            myFiles = file.list();  
            for (int i=0; i<myFiles.length; i++) {  
                File myFile = new File(file, myFiles[i]);   
                myFile.delete();  
            }  
         }  
Mogana
  • 262
  • 1
  • 4
  • 14