Here you can find the source of deleteFolder(Path path)
Parameter | Description |
---|---|
path | the path to the directory to delete. |
Parameter | Description |
---|---|
IOException | if something goes wrong. |
public static void deleteFolder(Path path) throws IOException
//package com.java2s; import java.io.IOException; import java.nio.file.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Main { /**//w w w .ja v a 2 s . c o m * Deletes a directory if it exists. * * @param path the path to the directory to delete. * @throws IOException if something goes wrong. */ public static void deleteFolder(Path path) throws IOException { deleteFolder(path, true); } /** * Deletes a directory if it exists. * * @param path the path to the directory to delete. * @param bypassNotEmptyDir flag that indicates to delete not empty folder. * @throws IOException if something goes wrong. */ public static void deleteFolder(Path path, boolean bypassNotEmptyDir) throws IOException { if (isFolder(path)) { if (bypassNotEmptyDir) { List<Path> listChildren = listChildren(path); for (Path children : listChildren) { if (isFolder(children)) { deleteFolder(children, bypassNotEmptyDir); } else { deleteFile(children); } } } Files.deleteIfExists(path); } } /** * Tests whether a file is a directory. * * @param path the path to the file to test. * @return true if the file is a directory; false if the file does not * exist, is not a directory, or it cannot be determined if the file * is a directory or not. */ public static boolean isFolder(Path path) { return Files.isDirectory(path); } /** * Gets children paths from the give directory. * * @param dir path to the directory. * @return the children paths from the give directory. * @throws IOException if something goes wrong. */ public static List<Path> listChildren(Path dir) throws IOException { return listChildren(dir, null); } /** * Gets children paths from the give directory appling the given filter. * * @param dir path to the directory. * @param filter the filter to be applied * @return the children paths from the give directory. * @throws IOException if something goes wrong. */ public static List<Path> listChildren(Path dir, DirectoryStream.Filter<? super Path> filter) throws IOException { if (isFolder(dir)) { List<Path> list = new ArrayList<>(); try (DirectoryStream<Path> directoryStream = (filter != null ? Files.newDirectoryStream(dir, filter) : Files.newDirectoryStream(dir))) { for (Path p : directoryStream) { list.add(p); } } return Collections.unmodifiableList(list); } return Collections.emptyList(); } /** * Deletes a file if it exists. * * @param path the path to the file to delete. * @throws IOException if something goes wrong. */ public static void deleteFile(Path path) throws IOException { if (!isFolder(path)) { Files.deleteIfExists(path); } } }