删除指定后缀的File文件
今天整理之前的下载的视频文件,发觉目录下有很多网站的快捷方式和一些不需要的文件,
对于有轻微强迫习惯的我,是看不惯的,就想到用学到的java知识,来删除这些文件.
import java.io.File;
/**
* File工具类
*/
public class FileUtils {
/**
* 删除指定路径下的指定后缀的文件
*
* @param filePath
* @param suffix
*/
public static void deleteFile(String filePath, String[] suffixs) {
File rootFile = new File(filePath);
if (filePath == null || !rootFile.exists()) {
throw new RuntimeException("指定的路径不存在!");
}
if (rootFile.isFile()) {
boolean suffix = checkFileSuffix(rootFile, suffixs);
if (suffix) {
System.out.println(rootFile.getAbsolutePath());
rootFile.delete();
}
} else {
deleteAllFile(rootFile, suffixs);
}
}
/**
* 删除所有的指定的后缀的文件
*
* @param directory
* 指定目录
* @param suffixs
* 指定后缀
*/
private static void deleteAllFile(File directory, String[] suffixs) {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
deleteAllFile(file, suffixs);
} else {
boolean b = checkFileSuffix(file, suffixs);
if (b) {
System.out.println(file.getAbsolutePath());
file.delete();
}
}
}
}
}
/**
* 校验文件是否以指定的后缀结尾
*
* @param file
* @param suffix
* @return
*/
private static boolean checkFileSuffix(File file, String[] suffixs) {
boolean b = false;
String path = file.getAbsolutePath();
for (String suffix : suffixs) {
if (path.endsWith(suffix)) {
b = true;
}
}
return b;
}
}
/**
* File测试类
*/
public class FileTest {
public static void main(String[] args) {
String[] suffixs = { "xxxxxx.lnk", "xxxxxx.url" };
String filePath = "D:/xxxxxx/xxxxx";
FileUtils.deleteFile(filePath, suffixs);
}
}