1. 程式人生 > >使用FilenameFilter來找出目錄下指定字尾的檔案

使用FilenameFilter來找出目錄下指定字尾的檔案

在專案中需要查詢指定目錄下特定字尾的檔案,在jdk官網上檢視資料時找到了FilenameFilter這個類,怎麼用也寫了,但是就是沒給個例子,對有些人實在有些不方便,這也是寫這篇文章的初衷,雖然簡單但希望能幫到需要的小夥伴們

下面直接入正題,給出demo程式:

package net.csdn.johnhuster;import java.io.File;import java.io.FilenameFilter;publicclassFileNameFilterDemo{
  //內部類
 public class FileFilter implements FilenameFilter
 {
    private String filterRule;
     public 
FileFilter(String filter) { this.filterRule = filter; }
     @Overridepublicboolean accept(File dir,String name){if(name.lastIndexOf('.')>0){// get last index for '.' charint lastIndex = name.lastIndexOf('.');// get extensionString str = name.substring(lastIndex);// match path name extension
if(str.equals(this.filterRule)){returntrue;}} return false;
}
 publicstaticvoid main(String[] args){File f =null;
File
[] paths;
FileNameFilterDemo fileFilter = new FileNameFilterDemo();
try{// create new file
f
=newFile("d:\\fileList");
// 檔案檔名字過濾器
FilenameFilter fileNameFilter =fileFilter
.newFileFilter(".txt");
// returns pathnames for files and directory

paths
= f.listFiles(fileNameFilter);// for each pathname in pathname array
for
(File path:paths){
// prints file and directory paths
System.out.println(path);}}catch(Exception e)
{
// if any error occurs
e
.printStackTrace();}}
}