ในตัวอย่าง เราจะใช้ FilenameFilter เพื่อลิสรายการไฟล์ทั้งหมดที่ลงท้ายด้วย ".txt" ในโฟรเดอร์ "C:\\users\\nopphanan7\\folder", และทำการลบ.
package demo.file; import java.io.*; public class FileChecker { /** * @param args */ private static final String FILE_DIR = "C:\\users\\nopphanan7\\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); if(dir.isDirectory()==false){ System.out.println("Directory does not exists : " + FILE_DIR); return; } // 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)); } } }ผลลัพธ์ที่ได้คือ
file : C:\users\nopphanan7\folder\newfile.txt is deleted : true
0 comments:
Post a Comment