Package Book.io;
Import Java.io.file;
public class Deletefileutil {
/**
* Delete file, can be a single file or folder
* @param filename to be deleted
* @return File deletion successfully returns TRUE, otherwise returns false
*/
public static Boolean Delete (string filename) {
File File = new file (filename);
if (!file.exists ()) {
System.out.println ("Delete file failed:" +filename+ "file does not exist");
return false;
}else{
if (File.isfile ()) {
return DeleteFile (filename);
}else{
return deletedirectory (filename);
}
}
}
/**
* Delete individual files
* @param filename of deleted file filename
* @return Single File Delete successfully returns TRUE, otherwise returns false
*/
public static Boolean DeleteFile (string filename) {
File File = new file (filename);
if (File.isfile () && file.exists ()) {
File.delete ();
System.out.println ("Delete single file" +filename+ "Success!") ");
return true;
}else{
System.out.println (Delete single file "+filename+" Failed!) ");
return false;
}
}
/**
* Delete directories (folders) and files under the directory
* @param dir The file path of the deleted directory
* @return Directory deletion successfully returns TRUE, otherwise returns false
*/
public static Boolean DeleteDirectory (String dir) {
If Dir does not end with a file separator, the file separator is automatically added
if (!dir.endswith (File.separator)) {
dir = dir+file.separator;
}
File Dirfile = new file (dir);
If the file for Dir does not exist, or if it is not a directory, exit
if (!dirfile.exists () | |!dirfile.isdirectory ()) {
System.out.println ("Delete directory failed" +dir+ directory does not exist!) ");
return false;
}
Boolean flag = true;
Delete all files under a folder (including subdirectories)
file[] files = dirfile.listfiles ();
for (int i=0;i<files.length;i++) {
Delete a child file
if (Files[i].isfile ()) {
Flag = DeleteFile (Files[i].getabsolutepath ());
if (!flag) {
Break
}
}
Deleting subdirectories
else{
Flag = DeleteDirectory (Files[i].getabsolutepath ());
if (!flag) {
Break
}
}
}
if (!flag) {
System.out.println ("Delete directory Failed");
return false;
}
Delete current directory
if (Dirfile.delete ()) {
System.out.println ("Delete directory" +dir+ "Success!") ");
return true;
}else{
System.out.println (Delete directory "+dir+" failed!) ");
return false;
}
}
public static void Main (string[] args) {
string filename = "G:/temp/xwz.txt";
Deletefileutil.deletefile (filename);
String filedir = "G:/TEMP/TEMP0/TEMP1";
Deletefileutil.deletedirectory (Filedir);
Deletefileutil.delete (Filedir);
}
}