java如何刪除某種擴展名的文件?
當前實例版本:61 0 評論 2215 瀏覽 發布於:2013年12月03 20:42 編輯+新實例

在Java中,你可以實現了 FilenameFilter,重寫accept(File dir, String name)方法,執行該文件過濾功能。

在這個例子中,我們將向您展示如何使用FilenameFilter,列出的都是文件夾“c:\\folder” 裡所有文件擴展名以“.txt” 結束的文件,然後將其刪除。

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));
       }
    }
}