How to delete a folder containing other folders in Java?
•
Java
See English answers > delete directories recursively in Java 23
import java.io.*; public class file03 { public static void main(String[] args) { File f1 = new File("C:/tempo1/tempo"); f1.mkdirs(); File f2 = new File("C:/test"); if(!f2.exists()) { f2.mkdir(); } f1 = new File("C:/tempo1/kempo"); f1.mkdirs(); f1 = new File("C:/tempo1"); String[] t = {}; if(f1.exists()) { t = f1.list(); System.out.println(t.length + " files found"); } for(int i = 0; i < t.length; i++) { System.out.println(t[i]); } try { Thread.sleep(3000); } catch(Exception e) {} f2.delete(); f2 = new File("C:/tempo1/test.txt"); try { f2.createNewFile(); } catch(Exception e) {} try { Thread.sleep(7000); } catch(Exception e) {} File f3 = new File("C:/tempo1/renametesting.txt"); f2.renameTo(f3); try { Thread.sleep(5000); } catch(Exception e) {} f3 = new File("C:/tempo1"); f3.delete(); } }
I noticed that when the folder test is deleted, the folder tempo1 will not be deleted Is it because it contains other folders and files? If so, how can I delete it? I'm using the BlueJ ide
Solution
To delete a folder that contains files, no circular or recursive search is required You can directly use:
FileUtils.deleteDirectory(<File object of directory>);
This function will delete the folder and all files in it
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码