Java刪除文件夾和文件
1 驗證傳入路徑是否為正確的路徑名
private static String matches = "[A-Za-z]:\\\\[^:?\"><*]*"; // 正則表達式,通過sPath.matches(matches)判斷
2 通用刪除方法,直接調用此方法,即可實現刪除文件夾或文件,包括文件夾下的所有文件
public boolean DeleteFolder(String sPath) {
flag = false;
file = new File(sPath);
// 判斷目錄或文件是否存在
if (!file.exists()) {
return flag;
} else {
// 判斷是否為文件
if (file.isFile()) {
return deleteFile(sPath);
} else {
// 為目錄時調用刪除目錄方法
return deleteDirectory(sPath);
}
}
}
3 實現刪除文件的方法
public boolean deleteFile(String sPath) {
flag = false;
file = new File(sPath);
// 路徑為文件且不為空則進行刪除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
4 刪除目錄(文件夾)以及目錄下的文件
public boolean deleteDirectory(String sPath) {
// sPath不以文件分隔符結尾,自動添加文件分隔符
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
File dirFile = new File(sPath);
// dir對應的文件不存在,或者不是一個目錄,則退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
flag = true;
// 刪除文件夾下的所有文件(包括子目錄)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 刪除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag) break;
}
// 刪除子目錄
else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag) break;
}
}
if (!flag) return false;
// 刪除當前目錄
if (dirFile.delete()) {
return true;
} else {
return false;
}
}
5 測試
public static void main(String[] args) {
HandleFileClass hfc = new HandleFileClass();
String path = "D:\\Abc\\123\\Ab1";
boolean result = hfc.CreateFolder(path);
System.out.println(result);
path = "D:\\Abc\\124";
result = hfc.DeleteFolder(path);
System.out.println(result);
}
原帖地址:https://blog.163.com/wu_huiqiang@126/blog/static/3718162320091022103144516/
最後更新:2017-04-03 16:49:08