To delete a file by using a recursive method

Source: Internet
Author: User
Tags empty
Recursively deleting a non-empty directory is not simply creating a file object, and then calling Delete () can be done. To safely delete a non-empty directory in a platform-independent way, you need an algorithm. The algorithm first deletes the file and then deletes all of its directories from the bottom of the directory tree.





all files in the directory can be purged by simply looping through the directory to find the file, and then calling Delete:


static public void Emptydirectory (File directory) {


file[] entries = Directory.listfiles ();


for (int i=0; i<entries.length; i++) {


Entries[i].delete ();


    }


}


This simple method can also be used to delete the entire directory structure. When a directory is encountered in a loop it recursively invokes DeleteDirectory, and it also checks whether the incoming argument is a real directory. Finally, it deletes the entire directory passed in as a parameter.


static public void DeleteDirectory (File dir) throws IOException {


if (dir = null) | |!dir.isdirectory) {


throw new IllegalArgumentException (


"Argument" +dir+ "is not a directory."


              );


    }





file[] entries = Dir.listfiles ();


int sz = entries.length;





for (int i=0; i<sz; i++) {


if (entries[i].isdirectory ()) {


deletedirectory (Entries[i]);


} else {


Entries[i].delete ();


        }


}





Dir.delete ();


}


has no File.listfiles method in Java 1.1 and some J2me/personaljava variants. So you can only use File.list, its return value is an array of strings, you want to construct a new file object for each string.





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.