eliminar carpeta de java [duplicar]


Esta pregunta ya tiene una respuesta aquí:

En Java, quiero eliminar todos los contenidos que están presentes en una carpeta que incluye archivos y carpetas.

public void startDeleting(String path) {
        List<String> filesList = new ArrayList<String>();
        List<String> folderList = new ArrayList<String>();
        fetchCompleteList(filesList, folderList, path);
        for(String filePath : filesList) {
            File tempFile = new File(filePath);
            tempFile.delete();
        }
        for(String filePath : folderList) {
            File tempFile = new File(filePath);
            tempFile.delete();
        }
    }

private void fetchCompleteList(List<String> filesList, 
    List<String> folderList, String path) {
    File file = new File(path);
    File[] listOfFile = file.listFiles();
    for(File tempFile : listOfFile) {
        if(tempFile.isDirectory()) {
            folderList.add(tempFile.getAbsolutePath());
            fetchCompleteList(filesList, 
                folderList, tempFile.getAbsolutePath());
        } else {
            filesList.add(tempFile.getAbsolutePath());
        }

    }

}

Este código no funciona, ¿cuál es la mejor manera de hacerlo?

Author: Eric Leschinski, 2010-09-23

11 answers

Si utilizas Apache Commons IO es de una sola línea:

FileUtils.deleteDirectory(dir);

Ver FileUtils.deleteDirectory()


Guayaba se usa para soportar funcionalidades similares:

Files.deleteRecursively(dir);

Esto ha sido eliminado de Guava hace varios lanzamientos.


Si bien la versión anterior es muy simple, también es bastante peligrosa, ya que hace muchas suposiciones sin decírtelo. Así que si bien puede ser seguro en la mayoría de los casos, prefiero la" forma oficial " de hacer it (desde Java 7):

public static void deleteFileOrFolder(final Path path) throws IOException {
  Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
    @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
      throws IOException {
      Files.delete(file);
      return CONTINUE;
    }

    @Override public FileVisitResult visitFileFailed(final Path file, final IOException e) {
      return handleException(e);
    }

    private FileVisitResult handleException(final IOException e) {
      e.printStackTrace(); // replace with more robust error handling
      return TERMINATE;
    }

    @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException e)
      throws IOException {
      if(e!=null)return handleException(e);
      Files.delete(dir);
      return CONTINUE;
    }
  });
};
 133
Author: Sean Patrick Floyd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-13 10:14:30

Tengo algo como esto :

public static boolean deleteDirectory(File directory) {
    if(directory.exists()){
        File[] files = directory.listFiles();
        if(null!=files){
            for(int i=0; i<files.length; i++) {
                if(files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                }
                else {
                    files[i].delete();
                }
            }
        }
    }
    return(directory.delete());
}
 83
Author: oyo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-21 15:37:55

Prueba esto:

public static boolean deleteDir(File dir) 
{ 
  if (dir.isDirectory()) 
  { 
    String[] children = dir.list(); 
    for (int i=0; i<children.length; i++)
      return deleteDir(new File(dir, children[i])); 
  }  
  // The directory is now empty or this is a file so delete it 
  return dir.delete(); 
} 
 7
Author: Sidharth Panwar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-07 06:39:50

Podría ser un problema con las carpetas anidadas. El código elimina las carpetas en el orden en que se encontraron, que es de arriba hacia abajo, que no funciona. Podría funcionar si primero inviertes la lista de carpetas.

Pero te recomiendo que uses una biblioteca como Commons IO para esto.

 6
Author: Thilo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-23 05:50:02

Encontré esta pieza de código más comprensible y funcional:

public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete(); // The directory is empty now and can be deleted.
}
 5
Author: Zon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-19 15:24:32

Usando los archivos .El método deleteDirectory() puede ayudar a simplificar el proceso de eliminar el directorio y todo lo que está debajo de él recursivamente.

Marque esta pregunta

 3
Author: ahvargas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:03:02

Escribí un método para esto hace algún tiempo. Elimina el directorio especificado y devuelve true si la eliminación del directorio se realizó correctamente.

/**
 * Delets a dir recursively deleting anything inside it.
 * @param dir The dir to delete
 * @return true if the dir was successfully deleted
 */
public static boolean deleteDirectory(File dir) {
    if(! dir.exists() || !dir.isDirectory())    {
        return false;
    }

    String[] files = dir.list();
    for(int i = 0, len = files.length; i < len; i++)    {
        File f = new File(dir, files[i]);
        if(f.isDirectory()) {
            deleteDirectory(f);
        }else   {
            f.delete();
        }
    }
    return dir.delete();
}
 2
Author: naikus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-23 06:20:41

Está almacenando todos los (sub) archivos y carpetas recursivamente en una lista, pero con su código actual almacena la carpeta padre antes de almacenar los hijos. Y así intenta eliminar la carpeta antes de que esté vacía. Prueba este código:

   if(tempFile.isDirectory()) {
        // children first
        fetchCompleteList(filesList, folderList, tempFile.getAbsolutePath());
        // parent folder last
        folderList.add(tempFile.getAbsolutePath());
   }
 1
Author: Andreas_D,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-23 05:53:44

El archivo javadoc para .borrar()

Booleano público delete ()

Elimina el archivo o directorio denotado por esta ruta abstracta. Si esta ruta > denota un directorio, entonces el directorio debe estar vacío para ser eliminado.

Así que una carpeta tiene que estar vacía o eliminarla fallará. Su código actualmente llena la lista de carpetas con la carpeta más importante primero, seguida de sus subcarpetas. Ya que iterar a través de la lista de la misma manera que intentará eliminar la carpeta superior antes de eliminar sus subcarpetas, esto fallará.

Cambiando estas líneas

    for(String filePath : folderList) {
        File tempFile = new File(filePath);
        tempFile.delete();
    }

A esto

    for(int i = folderList.size()-1;i>=0;i--) {
        File tempFile = new File(folderList.get(i));
        tempFile.delete();
    }

Debe hacer que su código elimine las subcarpetas primero.

La operación de eliminación también devuelve false cuando falla, por lo que puede verificar este valor para hacer algún manejo de errores si es necesario.

 1
Author: josefx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-23 06:22:28

Primero debe eliminar el archivo de la carpeta , luego la carpeta.De esta manera llamarás recursivamente al método.

 1
Author: Dead Programmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-23 07:11:13

Eliminará una carpeta recursivamente

public static void folderdel(String path){
    File f= new File(path);
    if(f.exists()){
        String[] list= f.list();
        if(list.length==0){
            if(f.delete()){
                System.out.println("folder deleted");
                return;
            }
        }
        else {
            for(int i=0; i<list.length ;i++){
                File f1= new File(path+"\\"+list[i]);
                if(f1.isFile()&& f1.exists()){
                    f1.delete();
                }
                if(f1.isDirectory()){
                    folderdel(""+f1);
                }
            }
            folderdel(path);
        }
    }
}
 -1
Author: Rishabh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-18 19:50:20