Java Android Delete files and folders function __ function

Source: Internet
Author: User
Tags file separator
/**
* Delete individual files
* @param the filename of the deleted file FilePath
* @return File deletion successfully returns TRUE, otherwise returns false
*/
public boolean DeleteFile (String filePath) {
File File = new file (FilePath);
if (File.isfile () && file.exists ()) {
return File.delete ();
}
return false;
}

/**
* Delete folders and files in the directory
* @param filePath The file path of the deleted directory
* @return Directory deletion successfully returns TRUE, otherwise returns false
*/
public boolean deletedirectory (String filePath) {
Boolean flag = false;
If FilePath does not end with a file delimiter, the file separator is automatically added
if (!filepath.endswith (File.separator)) {
FilePath = FilePath + file.separator;
}
File Dirfile = new file (FilePath);
if (!dirfile.exists () | |!dirfile.isdirectory ()) {
return false;
}
Flag = true;
file[] files = dirfile.listfiles ();
Traverse all files under the Delete folder (including subdirectories)
for (int i = 0; i < files.length; i++) {
if (Files[i].isfile ()) {
Delete a child file
Flag = DeleteFile (Files[i].getabsolutepath ());
if (!flag) break;
} else {
Deleting subdirectories
Flag = DeleteDirectory (Files[i].getabsolutepath ());
if (!flag) break;
}
}
if (!flag) return false;
Deletes the current empty directory
return Dirfile.delete ();
}

/**
* Deletes the specified directory or file according to the path, whether it exists or not
* @param filePath the directory or file to be deleted
* @return Delete succeeds returns True, otherwise returns false.
*/
public boolean DeleteFolder (String filePath) {
File File = new file (FilePath);
if (!file.exists ()) {
return false;
} else {
if (File.isfile ()) {
Call Delete File method for file
return DeleteFile (FilePath);
} else {
Call Delete directory method for directory
return DeleteDirectory (FilePath);
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.