usuwanie folderu z Javy [duplikat]

To pytanie ma już odpowiedź tutaj:

W Javie chcę usunąć całą zawartość zawartą w folderze zawierającym pliki i foldery.

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());
        }

    }

}

Ten kod nie działa, jaki jest najlepszy sposób, aby to zrobić?

Author: Eric Leschinski, 2010-09-23

11 answers

Jeśli używasz Apache Commons IO jest to jednolinijkowy:

FileUtils.deleteDirectory(dir);

Zobacz FileUtils.deleteDirectory()


Guava używane do obsługi podobnej funkcjonalności:

Files.deleteRecursively(dir);
To zostało usunięte z Guava kilka wydań temu.

Podczas gdy powyższa wersja jest bardzo prosta, jest również dość niebezpieczna, ponieważ robi wiele założeń bez mówienia. Tak więc, chociaż może to być bezpieczne w większości przypadków, wolę "oficjalny sposób" zrobić it (od 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-13 10:14:30

Mam coś takiego:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-21 15:37:55

Spróbuj tego:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-07 06:39:50

To może być problem z zagnieżdżonymi folderami. Twój kod usuwa foldery w kolejności, w jakiej zostały znalezione, czyli odgórnie, co nie działa. Może to zadziałać, jeśli najpierw odwrócisz listę folderów.

Ale polecam po prostu użyć biblioteki takiej jak Commons IO do tego.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-23 05:50:02

Znalazłem ten kawałek kodu bardziej underdadable i działa:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-19 15:24:32

Używanie Plików .metoda deleteDirectory () może pomóc w uproszczeniu procesu usuwania katalogu i wszystkiego, co znajduje się pod nim rekurencyjnie.

Sprawdź to pytanie

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:03:02

Kiedyś napisałem na to metodę. Usuwa Podany katalog i zwraca true, jeśli usunięcie katalogu powiodło się.

/**
 * 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/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-23 06:20:41

Przechowujesz rekurencyjnie wszystkie (pod) pliki i folder na liście, ale z bieżącym kodem przechowujesz folder nadrzędny przed przechowujesz dzieci. Więc spróbuj usunąć folder, zanim będzie pusty. Wypróbuj ten kod:

   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/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-23 05:53:44

Javadoc dla pliku.usunąć()

Public Boolean delete ()

Usuwa plik lub katalog oznaczony tą abstrakcyjną nazwą ścieżki. Jeśli ścieżka > oznacza katalog, wtedy katalog musi być pusty, aby został usunięty.

Więc folder musi być pusty lub usunięcie go nie powiedzie się. Kod aktualnie wypełnia listę folderów najpierw folderem top most, a następnie jego podfolderami. Ponieważ przeglądasz listę w ten sam sposób, co spróbuje usunąć najbardziej górny folder przed usunięciem jego podfolderów, to się nie powiedzie.

Zmiana linii

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

Do tego

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

Powinien spowodować, że kod najpierw usunie podfoldery.

Operacja delete również zwraca false, gdy się nie powiedzie, więc możesz sprawdzić tę wartość, aby w razie potrzeby wykonać obsługę błędów.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-23 06:22:28

Najpierw należy usunąć plik z folderu , a następnie folder.W ten sposób wywołasz rekurencyjnie metodę.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-23 07:11:13

Usunie katalog rekurencyjnie

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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-18 19:50:20