Java operations for deleting files and folders

Source: Internet
Author: User
Tags file separator

Java operations for deleting files and folders

/*** Delete a single file ** @ param sPath * path of the deleted file + file name * @ return true if a single file is deleted successfully, otherwise, false */public static boolean deleteFile (String sPath) {Boolean flag = false; File file = new File (sPath ); // Delete if (file. isFile () & file. exists () {file. delete (); flag = true;} return flag;}/*** delete directory (folder) and the file in the directory ** @ param sPath * is the file path of the deleted directory * @ return: returns true if the directory is deleted successfully; otherwise, returns false */public static boolean deleteDirectory (S Tring sPath) {// if sPath does not end with a file separator, the file separator if (! SPath. endsWith (File. separator) {sPath = sPath + File. separator;} File dirFile = new File (sPath); // exit if (! DirFile. exists () |! DirFile. isDirectory () {return false;} Boolean flag = true; // delete all files in the folder (including subdirectories) File [] files = dirFile. listFiles (); for (int I = 0; I <files. length; I ++) {// Delete the sub-file if (files [I]. isFile () {flag = deleteFile (files [I]. getAbsolutePath (); if (! Flag) break;} // Delete the subdirectory else {flag = deleteDirectory (files [I]. getAbsolutePath (); if (! Flag) break;} if (! Flag) return false; // delete the current directory if (dirFile. delete () {return true;} else {return false ;}}

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.