通用的文件夹或文件删除方法,直接调用此方法,即可实现删除文件夹或文件,包括文件夹下的所有文件
- 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) {
-
- if (!sPath.endsWith(File.separator)) {
- sPath = sPath + File.separator;
- }
- File dirFile = new File(sPath);
-
- 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,main() 方法
- 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);
-
- }
Java删除文件夹和文件,布布扣,bubuko.com
Java删除文件夹和文件
原文:http://www.cnblogs.com/564085446java/p/3837072.html