Files are deleted as subfiles.

Source: Internet
Author: User

Files are deleted as subfiles.

First, I will briefly describe some basics: (the folder mentioned below is the directory. I did not know what the directory is at first, and then I learned that the directory is the folder ).

1. First, we will introduce the basic usage of the delete () method.

Create a File object first, for example, File file = new File ("C:/text"). text is a folder;

① When the text in the folder is empty (that is, there is nothing in it), call the file. delete () method to delete the file and return true.

② When the text in the folder is not empty (there are folders or files in it) and the file. delete () method is called, the file is not deleted and false is returned.

③ When there is something in the folder, it cannot be deleted directly.

2. recursion: A simple understanding is to call yourself.

3. encapsulate a method to delete a folder, that is, its subfiles:

1 public static void deleteDir (File file) {2 if (file. exists () {// determines whether the passed object exists. If yes, run the following code 3 File [] fileList = file. listFiles (); 4 for (File f: fileList) {5 if (f. isDirectory () {// 6 deleteDir (f) When the file is a folder; // recursive 7} else {8 System is used here. out. println ("the deleted file is:" + f. getName (); 9 f. delete (); 10} 11} 12 System. out. println ("the deleted folder is:" + file. getName (); // Delete the empty folder 13 file on the outermost layer. delete (); 14} else {15 System. out. println ("the file you deleted does not exist"); 16} 17}

4. Call the following in the main function:

1 public static void main(String[] args) {2         File file = new File("C:/text");3          deleteDir(file);4     }

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.