import java.io.File;
/**
* 文件以及文件夹的复制
*
* @author DLHC
*
*/
public class FileDelete {
/**
* 主方法
*
* @param args
*/
public static void main(String[] args) {
// 文件删除
if (fileDelete("D:\\text\\1\\a.txt")) {
System.out.print("success");
} else {
System.out.print("file");
}
// 文件夹删除
if (fileDelete("D:\\text\\1")) {
System.out.print("success");
} else {
System.out.print("file");
}
}
/**
* 删除文件或者整个文件夹
*
* @param Path String 文件或者文件夹路径 如:d:/a.txt 或者 d:/a
* @return boolean
*/
public static boolean fileDelete(String Path) {
try {
if (!Path.endsWith(File.separator)) { // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
Path = Path + File.separator;
}
File file = new File(Path);
if (file.isDirectory()) {
String[] fileList = file.list();
File temp = null;
for (int i = 0; i < fileList.length; i++) {
temp = new File(Path + fileList[i]);
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) { // 如果是子文件夹 进行递归操作
fileDelete(Path + "/" + fileList[i]);
}
}
file.delete();
}
if (file.exists()) {
file.delete();
}
} catch (Exception e) {
return false;
}
return true;
}
}
Java 文件或者文件夹的删除
最新推荐文章于 2022-10-20 23:17:07 发布