1. Recursively delete files
Suppose a folder below also have subfolders, delete the words will be error, this time to use a recursive way to delete all files in this file folder and folders
Package Cn.itcast.digui;import java.io.file;/** * Recursive removal of all files contained in the demo directory * Analysis: * A: Packaging directory * B: Get all Files or directories under the directory * C: Traverse the file array to get each A File Object * D: Infer that the file object is both directory * Yes: Back to B * No: Delete * @author Administrator * */public class Giguidelete {public static void Mai N (string[] args) {file Srcfile=new file ("demo");d Eletefolder (srcfile);} private static void DeleteFolder (file srcfile) {file[] files = srcfile.listfiles (); for (file f:files) {if (F.isdirectory () {DeleteFolder (f);//Recursive Call}ELSE{SYSTEM.OUT.PRINTLN (F.getname () + "---" +f.delete ());//delete file}}system.out.println ( Srcfile.getname () + "---" +srcfile.delete ());//Delete Empty Directory}}
For test results, the debug test can be done, here I do not test!
2. Get the absolute path of all the. jpg files in the folder folder
Package Cn.itcast_03;import java.io.file;/* * Requirements: Please send the absolute path of all Java end files under the E:\JavaSE folder to the console.* * Analysis: * A: Package folder * B: Get all files or folders under the folder file array * C: Traverse the file array. Get each File Object * D: Infer If the file object is a folder * Yes: Go back to B * No: Continue to infer whether to end with. Java * Yes: output the absolute path of the file * No: Ignore it */public class Filepathdemo {public STA tic void Main (string[] args) {//encapsulation folder File Srcfolder = new file ("E:\\javase");//recursive function implementation getalljavafilepaths (Srcfolder);} private static void Getalljavafilepaths (file srcfolder) {//Gets the file array of all files or folders under this folder file[] Filearray = Srcfolder.listfiles ();//traverse the file array to get each file object for (file File:filearray) {//infer if the file object is a folder if (File.isdirectory ()) { Getalljavafilepaths (file);} else {//continue to infer whether to end with. Java if (File.getname (). EndsWith (". Java")) {//To output the absolute path of the file System.out.println (file.getabsolutepath ());}}}}}
For testing you can use debug mode to view
Javase file Recursively delete & get the absolute path of all the. jpg files in the folder folder