23 ответов:
Java не может удалить папки с данными в нем. Вы должны удалить все файлы перед удалением папки.
использовать что-то вроде:
String[]entries = index.list(); for(String s: entries){ File currentFile = new File(index.getPath(),s); currentFile.delete(); }затем вы должны быть в состоянии удалить папку с помощью
index.delete()Непроверенные!
просто один лайнер.
import org.apache.commons.io.FileUtils; FileUtils.deleteDirectory(new File(destination));документация здесь
это работает, и хотя кажется неэффективным пропустить тест каталога, это не так: тест происходит сразу в
listFiles().void deleteDir(File file) { File[] contents = file.listFiles(); if (contents != null) { for (File f : contents) { deleteDir(f); } } file.delete(); }обновление, чтобы избежать следующих символических ссылок:
void deleteDir(File file) { File[] contents = file.listFiles(); if (contents != null) { for (File f : contents) { if (! Files.isSymbolicLink(f.toPath())) { deleteDir(f); } } } file.delete(); }
в JDK 7 Вы можете использовать
Files.walkFileTree()иFiles.deleteIfExists()для удаления дерева файлов.в JDK 6 одним из возможных способов является использование FileUtils.deleteQuietly из Apache Commons, который удалит файл, каталог или каталог с файлами и подкаталогами.
используя Apache Commons-IO, он следует за однострочным:
import org.apache.commons.io.FileUtils; FileUtils.forceDelete(new File(destination));Это (немного) более эффективно, чем
FileUtils.deleteDirectory.
Я предпочитаю это решение на java 8:
Files.walk(pathToBeDeleted) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete);С этого сайта: http://www.baeldung.com/java-delete-directory
моя основная рекурсивная версия, работающая с более старыми версиями JDK:
public static void deleteFile(File element) { if (element.isDirectory()) { for (File sub : element.listFiles()) { deleteFile(sub); } } element.delete(); }
Это лучшее решение для
Java 7+:public static void deleteDirectory(String directoryFilePath) throws IOException { Path directory = Paths.get(directoryFilePath); if (Files.exists(directory)) { Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException { Files.delete(path); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path directory, IOException ioException) throws IOException { Files.delete(directory); return FileVisitResult.CONTINUE; } }); } }
Мне нравится это решение больше всего. Он не использует стороннюю библиотеку, вместо этого он использует NIO2 из Java 7.
/** * Deletes Folder with all of its content * * @param folder path to folder which should be deleted */ public static void deleteFolderAndItsContent(final Path folder) throws IOException { Files.walkFileTree(folder, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc != null) { throw exc; } Files.delete(dir); return FileVisitResult.CONTINUE; } }); }
в этой
index.delete(); if (!index.exists()) { index.mkdir(); }вы призываете
if (!index.exists()) { index.mkdir(); }после
index.delete();это означает, что вы создаете файл снова после удаления .удалить() возвращает логическое значение value.So если вы хотите проверить, то сделайте
System.out.println(index.delete());если выtrueто это означает, что файл удаленFile index = new File("/home/Work/Indexer1"); if (!index.exists()) { index.mkdir(); } else{ System.out.println(index.delete());//If you get true then file is deleted if (!index.exists()) { index.mkdir();// here you are creating again after deleting the file } }С комментарии приведенный ниже, обновленный ответ выглядит так
File f=new File("full_path");//full path like c:/home/ri if(f.exists()) { f.delete(); } else { try { //f.createNewFile();//this will create a file f.mkdir();//this create a folder } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
гуава 21+ на помощь. Используйте только если нет символических ссылок, указывающих на удаляемый каталог.
com.google.common.io.MoreFiles.deleteRecursively( file.toPath(), RecursiveDeleteOption.ALLOW_INSECURE ) ;(этот вопрос хорошо индексируется Google, поэтому другие люди usig Guava могут быть рады найти этот ответ, даже если он избыточен с другими ответами в другом месте.)
directry не может просто удалить, если у него есть файлы, поэтому вам может потребоваться сначала удалить файлы внутри, а затем каталог
public class DeleteFileFolder { public DeleteFileFolder(String path) { File file = new File(path); if(file.exists()) { do{ delete(file); }while(file.exists()); }else { System.out.println("File or Folder not found : "+path); } } private void delete(File file) { if(file.isDirectory()) { String fileList[] = file.list(); if(fileList.length == 0) { System.out.println("Deleting Directory : "+file.getPath()); file.delete(); }else { int size = fileList.length; for(int i = 0 ; i < size ; i++) { String fileName = fileList[i]; System.out.println("File path : "+file.getPath()+" and name :"+fileName); String fullPath = file.getPath()+"/"+fileName; File fileOrFolder = new File(fullPath); System.out.println("Full Path :"+fileOrFolder.getPath()); delete(fileOrFolder); } } }else { System.out.println("Deleting file : "+file.getPath()); file.delete(); } }
Если у вас есть подпапки, вы найдете проблемы с ответами Cemron. поэтому вы должны создать метод, который работает так:
private void deleteTempFile(File tempFile) { try { if(tempFile.isDirectory()){ File[] entries = tempFile.listFiles(); for(File currentFile: entries){ deleteTempFile(currentFile); } tempFile.delete(); }else{ tempFile.delete(); } getLogger().info("DELETED Temporal File: " + tempFile.getPath()); } catch(Throwable t) { getLogger().error("Could not DELETE file: " + tempFile.getPath(), t); } }
вы можете сделать рекурсивный вызов, если подкаталоги существуют
import java.io.File; class DeleteDir { public static void main(String args[]) { deleteDirectory(new File(args[0])); } static public boolean deleteDirectory(File path) { if( path.exists() ) { File[] files = path.listFiles(); for(int i=0; i<files.length; i++) { if(files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return( path.delete() ); } }
некоторые из этих ответов, кажется, излишне долго:
if (directory.exists()) { for (File file : directory.listFiles()) { file.delete(); } directory.delete(); }работает и для вложенных каталогов.
удалить его из другой части
File index = new File("/home/Work/Indexer1"); if (!index.exists()) { index.mkdir(); System.out.println("Dir Not present. Creating new one!"); } index.delete(); System.out.println("File deleted successfully");
вы можете попробовать следующие
File dir = new File("path"); if (dir.isDirectory()) { dir.delete(); }Если в вашей папке есть подпапки, вам может потребоваться рекурсивно удалить их.
private void deleteFileOrFolder(File file){ try { for (File f : file.listFiles()) { f.delete(); deleteFileOrFolder(f); } } catch (Exception e) { e.printStackTrace(System.err); } }
import org.apache.commons.io.FileUtils; List<String> directory = new ArrayList(); directory.add("test-output"); directory.add("Reports/executions"); directory.add("Reports/index.html"); directory.add("Reports/report.properties"); for(int count = 0 ; count < directory.size() ; count ++) { String destination = directory.get(count); deleteDirectory(destination); } public void deleteDirectory(String path) { File file = new File(path); if(file.isDirectory()){ System.out.println("Deleting Directory :" + path); try { FileUtils.deleteDirectory(new File(path)); //deletes the whole folder } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("Deleting File :" + path); //it is a simple file. Proceed for deletion file.delete(); } }работает как Шарм . Для папок и файлов . Салам:)
мы можем использовать
spring-coreзависимость;boolean result = FileSystemUtils.deleteRecursively(file);
большинство ответов (даже последние), ссылающихся на классы JDK, полагаются на
File.delete()но это ошибочный API, так как операция может завершиться беззвучно.
Элементjava.io.File.delete()документация по методу гласит:отметим, что
java.nio.file.Filesкласс определяетdeleteметод бросьтеIOExceptionкогда файл не может быть удален. Это полезно для сообщение об ошибке и для диагностики, почему файл не может быть удален.как замена, вы должны благоволить
Files.delete(Path p)что выдаетIOExceptionС сообщением об ошибке.фактический код может быть написан как :
Path index = Paths.get("/home/Work/Indexer1"); if (!Files.exists(index)) { index = Files.createDirectories(index); } else { Files.walk(index) .sorted(Comparator.reverseOrder()) // as the file tree is traversed depth-first and that deleted dirs have to be empty .forEach(t -> { try { Files.delete(t); } catch (IOException e) { // LOG the exception and potentially stop the processing } }); if (!Files.exists(index)) { index = Files.createDirectories(index); } }
создать папку -
File directory = new File("D:/Java/Example"); boolean isCreated = directory.mkdir();каталог удалить -
обратитесь к этому ресурсу для подробного объяснения -удалить каталог.
вы можете использовать эту функцию
public void delete() { File f = new File("E://implementation1/"); File[] files = f.listFiles(); for (File file : files) { file.delete(); } }
Comments