4

Here is a code I tried:

import java.io.*;
public class file03 {
    public static void main(String[] args) {
        File f1 = new File("C:/tempo1/tempo");
        f1.mkdirs();
        File f2 = new File("C:/test");
        if(!f2.exists()) {
            f2.mkdir();
        }
        f1 = new File("C:/tempo1/kempo");
        f1.mkdirs();
        f1 = new File("C:/tempo1");
        String[] t = {};
        if(f1.exists()) {
            t = f1.list();
            System.out.println(t.length + " files found");
        }
        for(int i = 0; i < t.length; i++) {
            System.out.println(t[i]);
        }
        try {
            Thread.sleep(3000);
        }
        catch(Exception e) {}
        f2.delete();
        f2 = new File("C:/tempo1/test.txt");
        try {
            f2.createNewFile();
        }
        catch(Exception e) {}
        try {
            Thread.sleep(7000);
        }
        catch(Exception e) {}
        File f3 = new File("C:/tempo1/renametesting.txt");
        f2.renameTo(f3);
        try {
            Thread.sleep(5000);
        }
        catch(Exception e) {}
        f3 = new File("C:/tempo1");
        f3.delete();
    }
}

what I noticed was that while the folder test gets deleted, the folder tempo1 doesn't get deleted. Is it because it contains other folders and files? If so, how can I delete it? I am using BlueJ IDE.

yashhy
  • 2,856
  • 5
  • 31
  • 57
user3177527
  • 65
  • 1
  • 5
  • 2
    I think you'll have to do it recursively – BackSlash Jan 24 '14 at 13:19
  • 1
    You will have to delete the files and dir recursively. – Rahul Jan 24 '14 at 13:20
  • But isn't there any other way to delete it directly? Deleting recursive sounds quite laborious. – user3177527 Jan 24 '14 at 13:39
  • The following post should help. It is similar to yours: [http://stackoverflow.com/questions/779519/delete-files-recursively-in-java][1] [1]: http://stackoverflow.com/questions/779519/delete-files-recursively-in-java – Bludzee Jan 24 '14 at 14:34

4 Answers4

5

A folder can not be deleted until all files of that folder are deleted.

First delete all files from that folder then delete that folder

This is code for deleting a folder..

You need to pass the path of the folder only

public static void delete(File file)
            throws IOException {

        if (file.isDirectory()) {

            //directory is empty, then delete it
            if (file.list().length == 0) {

                file.delete();
//                System.out.println("Directory is deleted : "+ file.getAbsolutePath());

            } else {

                //list all the directory contents
                String files[] = file.list();

                for (String temp : files) {
                    //construct the file structure
                    File fileDelete = new File(file, temp);

                    //recursive delete
                    delete(fileDelete);
                }

                //check the directory again, if empty then delete it
                if (file.list().length == 0) {
                    file.delete();
//                    System.out.println("Directory is deleted : " + file.getAbsolutePath());
                }
            }

        } else {
            //if file, then delete it
            file.delete();
//            System.out.println("File is deleted : " + file.getAbsolutePath());
        }
    }
AJ.
  • 4,526
  • 5
  • 29
  • 41
4
public class DeleteFolder {
/**
 * Delete a folder and all content folder & files.
 * @param folder
 */
  public void rmdir(final File folder) {     
      if (folder.isDirectory()) {           //Check if folder file is a real folder
          File[] list = folder.listFiles(); //Storing all file name within array
          if (list != null) {               //Checking list value is null or not to check folder containts atlest one file
              for (int i = 0; i < list.length; i++) {    
                  File tmpF = list[i];
                  if (tmpF.isDirectory()) {   //if folder  found within folder remove that folder using recursive method
                      rmdir(tmpF);
                  }
                  tmpF.delete();             //else delete file
              }
          }
          if (!folder.delete()) {            //if not able to delete folder print message
            System.out.println("can't delete folder : " + folder);
          }
      }
  }
}
Anupam Maiti
  • 1,570
  • 1
  • 19
  • 35
  • Totally the way i would do it! – omgBob Jan 24 '14 at 13:27
  • 3
    -1. "Just code" answers are not good to me. Because you show how to do it but you don't explain what you are doing, so the OP is learning nothing from this answer, he is just copying your code, and that's not the purpose of this site. – BackSlash Jan 24 '14 at 13:28
  • Any java coder can understand this small piece of code.And now i added comment for you. – Anupam Maiti Jan 24 '14 at 13:41
  • @anupammaiti No, if he doesn't know about recursion or if he just started programming probably he'll find it hard to understand the code. – BackSlash Jan 24 '14 at 13:43
  • Thanks a lot. But isn't there anything more direct? – user3177527 Jan 24 '14 at 13:44
  • He can Google it.if he is able to post his question in this site he can search what is recursion. – Anupam Maiti Jan 24 '14 at 13:47
  • I think this is the minimum code to fulfill your requirement using core java.If you wants to use other API like Apache commons IO then visit this link http://stackoverflow.com/questions/11447241/force-delete-all-files-from-a-folder – Anupam Maiti Jan 24 '14 at 13:50
  • @anupammaiti I think you are not getting the point. This site is here to **help** people understand how to do things, not to provide code saying "If you don't know what I'm doing search Google". – BackSlash Jan 24 '14 at 13:52
  • @BackSlash & anupammaiti: Thanks. I have the basic idea of what recursion is. And a full code certainly helps. It's just that I was looking for something that is more direct. Maybe a method like forceDelete() that will do the job. – user3177527 Jan 24 '14 at 13:53
  • Oh ok i got your point.......from the next time i will explain everything within the code...any more suggestion??? – Anupam Maiti Jan 24 '14 at 13:54
  • @anupammaiti : is the final before File folder necessary in your rmdir method? – user3177527 Jan 24 '14 at 14:10
  • No final is not necessary.. – Anupam Maiti Jan 24 '14 at 14:13
2

To delete folder having files , no need of loops or recursive search. You can directly use:

FileUtils.deleteDirectory(<File object of directory>);

This function will delete the folder and all files in it

Vasant PADHIYAR
  • 772
  • 5
  • 7
  • Thanks a lot. This seems to be more or less what I would want. Is this an in-built function? – user3177527 Jan 24 '14 at 13:59
  • I tried : FileUtils.deleteDirectory(f3); It says can't find symbol FileUtils. – user3177527 Jan 24 '14 at 14:03
  • Yes, its is part of Apache commons: org.apache.commons.io.FileUtils – Vasant PADHIYAR Jan 24 '14 at 14:03
  • import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; public class DeleteDirectory { public static void main(String[] args) { try { File directory = new File("/home/foobar/Temp/Data"); // // Deletes a directory recursively. When deletion process is fail an // IOException is thrown and that's why we catch the exception. // FileUtils.deleteDirectory(directory); } catch (IOException e) { e.printStackTrace(); } } } – Vasant PADHIYAR Jan 24 '14 at 14:07
  • How do you do: import org.apache.commons.io.FileUtils; It is giving an error. What exactly is apache commons? – user3177527 Jan 24 '14 at 14:48
0

You can use the commons io library FileUtils class :

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#deleteDirectory(java.io.File)

"Deletes a directory recursively."