1 Packagejavatest;2 3 ImportJava.io.File;4 Importjava.util.ArrayList;5 ImportJava.util.regex.Pattern;6 7 classFileUtils8 {9 Public Static voidMain (string[] args)Ten { OneString dir = "C:\\users\\hp\\desktop\\test"; A -System.out.println ("Recursively get all files in this directory:"); - for(File f:fileutils.getfilesrecursive (dir)) the { - System.out.println (F.getabsolutepath ()); - } - +System.out.println ("Recursively get all subdirectories under this directory:")); - for(File f:fileutils.getdirecotriesrecursive (dir)) + { A System.out.println (F.getabsolutepath ()); at } - -System.out.println ("Delete all. html files under this directory"); -Removefiles (dir,NULL); -System.out.println ("Done."); - } in - /*** * * * To get all the files in a directory recursively * * * **/ to Public StaticArraylist<file>getfilesrecursive (String dir) + { -arraylist<file> files =NewArraylist<file>(); the *File TargetDir =NewFile (dir); $ if(Targetdir.exists ())Panax Notoginseng { - for(File file:targetDir.listFiles ()) the { + if(File.isfile ()) A { the files.add (file); + } - Else if(File.isdirectory ()) $ { $ Files.addall (Getfilesrecursive (File.getabsolutepath ())); - } - } the } - Wuyi returnfiles; the } - Wu /*** * * * recursively get all subdirectories under a directory * * * **/ - Public StaticArraylist<file>getdirecotriesrecursive (String dir) About { $Arraylist<file> dirs =NewArraylist<file>(); - -File TargetDir =NewFile (dir); - if(Targetdir.exists ()) A { + for(File f:targetdir.listfiles ()) the { - if(F.isdirectory ()) $ { the Dirs.add (f); the Dirs.addall (Getdirecotriesrecursive (F.getabsolutepath ())); the } the } - } in the returndirs; the } About the /*** * * * * Delete all files under a directory where the file name matches the filter, then delete the empty subdirectory * * * **/ the Public Static voidremovefiles (String targetDir, string Fileregex) the { +arraylist<file> files =getfilesrecursive (targetDir); - //Delete all files and subdirectories in this directory without filtering criteria the if(Fileregex = =NULL|| Fileregex.equals ("") )Bayi { the //Delete all files first. the for(File file:files) - { - File.delete (); the } the //Remove all empty directories from the inside out. theArraylist<file> dirs=getdirecotriesrecursive (targetDir); the for(inti=0;i< dirs.size (); + +i) - { theDirs.get (Dirs.size ()-1-i). Delete (); the } the }94 Else the { the //filter file names with regular expressions thePattern Pat =Pattern.compile (Fileregex);98 for(File file:files) About { - if(Pat.matcher (File.getabsolutepath ()). Find ())101 File.delete ();102 }103 }104 } the}
Java get, delete files and directories