Delete a specified file
Example
In this example, it deletes the log file "c: \ logfile20100131.log ".
The code is as follows: |
Copy code |
Package com. yiibai. file; Import java. io. File; Public class DeleteFileExample { Public static void main (String [] args) { Try { File file = new File ("c: \ logfile20100131.log "); If (file. delete ()){ System. out. println (file. getName () + "is deleted! "); } Else { System. out. println ("Delete operation is failed ."); } } Catch (Exception e ){ E. printStackTrace (); } } } |
Delete a file with a certain extension
In this example, we will show you how to use FilenameFilter to list all files whose names end with the extension name "cmd.txt" in the "c: \ folder" folder, and then delete them.
The code is as follows: |
Copy code |
Package com. yiibai. io; Import java. io .*; Public class FileChecker { Private static final String FILE_DIR = "c: \ folder "; Private static final String FILE_TEXT_EXT = ". txt "; Public static void main (String args []) { New FileChecker (). deleteFile (FILE_DIR, FILE_TEXT_EXT ); } Public void deleteFile (String folder, String ext ){ GenericExtFilter filter = new GenericExtFilter (ext ); File dir = new File (folder ); // List out all the file name with. txt extension String [] list = dir. list (filter ); If (list. length = 0) return; File fileDelete; For (String file: list ){ String temp = new StringBuffer (FILE_DIR) . Append (File. separator) . Append (file). toString (); FileDelete = new File (temp ); Boolean isdeleted = fileDelete. delete (); System. out. println ("file:" + temp + "is deleted:" + isdeleted ); } } // Inner class, generic extension filter Public class GenericExtFilter implements FilenameFilter { Private String ext; Public GenericExtFilter (String ext ){ This. ext = ext; } Public boolean accept (File dir, String name ){ Return (name. endsWith (ext )); } } } |
Batch delete files
The code is as follows: |
Copy code |
File file = new File ("your_root") // all files are loaded here. If (file. exists () & file. isDirectory ()){ File. delete (); } |