Delete a file

Source: Internet
Author: User

Delete a file

Method 1: input a string for deletion

1 public static void delete (String path) {2 File file = new File (path); 3 // determine whether the File exists 4 if (! File. exists () {5 return; 6} 7 // yes. Delete 8 if (file. isFile () {9 file. delete (); 10 return; 11} 12 // is the directory 13 if (file. isDirectory () {14 String [] files = file. list (); 15 // Add the delimiter 16 if (! Path. endsWith (File. separator) {17 path = path + File. separator; 18} 19 20 for (int I = 0; I <files. length; I ++) {21 // recursive call to delete 22 delete (path + files [I]); 23} 24} 25 file. delete (); 26}

Method 2: input a file to delete the file.

1 public static void deleteAllFiles (File file) {2 // determine whether the File exists 3 if (! File. exists () {4 return; 5} 6 // yes. Delete 7 if (file. isFile () {8 file. delete (); 9 return; 10} 11 // directory 12 if (file. isDirectory () {13 // return the files and directories in this directory 14 File [] files = file. listFiles (); 15 // recursive call to delete 16 for (int I = 0; I <files. length; I ++) {17 deleteAllFiles (files [I]); 18} 19} 20 file. delete (); 21}

The difference between the two is that when a string is passed in, this string represents a directory, and you need to add separators to the files and directories under this directory.

 

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.