Java 删除文件和文件夹

一、删除文件夹及其子文件

/**
 * 【删除文件夹】
 * <p>
 * 删除文件夹及其子文件
 */
public class DelFilesOrFolders {
    
    
    public static void main(String args[]) {
    
    
        String folderPath = "/Users/mac/Desktop/var/";
        delFolder(folderPath);
    }

    /**
     * 删除文件夹
     *
     * @param folderPath 文件夹完整绝对路径
     */
    public static void delFolder(String folderPath) {
    
    
        try {
    
    
            delAllFile(folderPath); //删除里面的所有内容
            File myFilePath = new File(folderPath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 删除指定文件夹下所有文件
     *
     * @param folderPath 文件夹完整绝对路径
     */
    public static void delAllFile(String folderPath) {
    
    
        File file = new File(folderPath);
        if (!file.exists()) {
    
    
            return;
        }
        if (!file.isDirectory()) {
    
    
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
    
    
            if (folderPath.endsWith(File.separator)) {
    
    
                temp = new File(folderPath + tempList[i]);
            } else {
    
    
                temp = new File(folderPath + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
    
    
                temp.delete();
            } else if (temp.isDirectory()) {
    
    
                delAllFile(folderPath + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(folderPath + "/" + tempList[i]);//再删除空文件夹
            }
        }
    }
}

二、删除特定文件

/**
 * 【删除特定文件】
 * 删除10天前目标目录固定前缀的文件
 */
public class DelSpecificFile {
    
    
    public static void main(String args[]) {
    
    
        LocalDate now = LocalDate.now();
        LocalDate tenDaysAgo = now.plusDays(-10);
        String dateStr = tenDaysAgo.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        deleteFilesForPathByPrefix(Paths.get("/Users/mac/Desktop/var/"), "del." + dateStr);
    }

    public static void deleteFilesForPathByPrefix(final Path path, final String prefix) {
    
    
        try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path, prefix + "*")) {
    
    
            for (final Path newDirectoryStreamItem : newDirectoryStream) {
    
    
                Files.delete(newDirectoryStreamItem);
            }
        } catch (final Exception e) {
    
    
            e.printStackTrace();
        }
    }

}

猜你喜欢

转载自blog.csdn.net/ChineseSoftware/article/details/129032167