Here you can find the source of deleteRecursive(File src, List
public static void deleteRecursive(File src, List<File> excludes) throws IOException
//package com.java2s; /*/* w w w . j a v a2s. c o m*/ * Copyright (C) 2017 CenturyLink, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.IOException; import java.util.List; public class Main { public static void deleteRecursive(File src) throws IOException { deleteRecursive(src, null); } public static void deleteRecursive(File src, List<File> excludes) throws IOException { if (!src.exists()) throw new IOException("File/directory does not exist: " + src); if (excludes == null || !excludes.contains(src)) { if (src.isFile()) { if (!src.delete()) throw new IOException("Cannot delete file: " + src); } else { for (File srcFile : src.listFiles()) { if (srcFile.isFile()) { if (excludes == null || !excludes.contains(srcFile)) { if (!srcFile.delete()) throw new IOException("Cannot delete: " + srcFile); } } else if (srcFile.isDirectory()) { if (excludes == null || !excludes.contains(srcFile)) deleteRecursive(srcFile, excludes); } } boolean isParentOfExclude = false; if (excludes != null) { for (File exclude : excludes) { File parent = exclude.getParentFile(); while (!isParentOfExclude && parent != null) { isParentOfExclude = parent.equals(src); parent = parent.getParentFile(); } if (isParentOfExclude) break; // don't keep checking } } if (!isParentOfExclude) { if (!src.delete()) throw new IOException("Cannot delete: " + src); } } } } }