遍历删除指定目录下的指定文件--方便用的时候直接copy
本文连接:https://www.cnblogs.com/muphy/p/15620563.html
使用方式
javac DeleteFile.java -encoding utf-8 java DeleteFile "D:\\BaiduNetdiskDownload\\录播视频及资料" "录播视频"
DeleteFile.java
//package me.muphy; import java.io.File; /** * 遍历删除指定文件 * * @className: DeleteFile * @author: 若非 * @date: 2021-11-29 16:57 */ public class DeleteFile { public static void main(String[] args) { String pathname = "D:\\BaiduNetdiskDownload\\录播视频及资料"; String fileName = "录播视频"; if (args.length > 1) { pathname = args[0]; fileName = args[1]; } System.out.println("开始删除文件!"); deleteFile(pathname, fileName); System.out.println("删除文件完成!"); } private static void deleteFile(String pathname, String name) { File file = new File(pathname); if (file == null) { System.out.println("指定路径不存在!"); return; } if (!file.isDirectory()) { System.out.println("指定路径不是文件夹路径!"); return; } if (name == null || name.trim().isEmpty()) { System.out.println("删除文件名不能为空!"); return; } for (File listFile : file.listFiles()) { if (listFile.getName().equals(name)) { deleteFile(listFile); continue; } if (listFile.isDirectory()) { deleteFile(listFile.getAbsolutePath(), name); } } } private static void deleteFile(File file) { if (file == null) { return; } String path = file.getAbsolutePath(); if (file.isFile()) { boolean delete = false; try { delete = file.delete(); } catch (Exception e) { e.printStackTrace(); } if (delete) { System.out.println("已删除文件:" + path); } else { System.out.println("删除文件失败:" + path); } return; } if (file.isDirectory()) { for (File listFile : file.listFiles()) { deleteFile(listFile); } boolean delete = file.delete(); if (delete) { System.out.println("已删除目录:" + path); } else { System.out.println("删除目录失败:" + path); } } } }