How to delete folders in Java

Source: Internet
Author: User

How to delete folders in Java

 
File file = new file ("D:/defonds/Temp ");

If "D:/defonds/Temp" is an empty directory, it can be deleted successfully. However, if it is a non-empty directory, it cannot be deleted successfully. You must delete its sub-files (directories) to delete them successfully. You can use the following methods to successfully delete a non-empty folder:

 
// Recursively Delete the private void deletefile (File file) {If (file. exists () {// determine whether the object exists if (file. isfile () {// checks whether the file is a file. delete (); // delete file} else if (file. isdirectory () {// otherwise, if it is a directory file [] files = file. listfiles (); // declare all files in the directory []; for (INT I = 0; I <files. length; I ++) {// traverse all files in the directory this. deletefile (files [I]); // use this method to iterate each file} file. delete (); // Delete folder} else {system. out. println ("the deleted file does not exist ");}}

You can also use the following method:

 Public static void deleteallfilesofdir (file path) {If (! Path. exists () return; If (path. isfile () {path. delete (); return;} file [] files = path. listfiles (); For (INT I = 0; I 
  

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.