In Java, I want to delete all the contents that are present in a folder which includes files and folders.
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()); } } }
This code does not work, what is the best way to do this?
The delete() method of the File class deletes the file/directory represented by the current File object. This ListFiles() method of the File class returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.
If you use Apache Commons IO it's a one-liner:
FileUtils.deleteDirectory(dir);
See FileUtils.deleteDirectory()
Guava used to support similar functionality:
Files.deleteRecursively(dir);
This has been removed from Guava several releases ago.
While the above version is very simple, it is also pretty dangerous, as it makes a lot of assumptions without telling you. So while it may be safe in most cases, I prefer the "official way" to do it (since 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; } }); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With