Java 文件过滤 FileFilter

来源:互联网 发布:java培训课 编辑:程序博客网 时间:2024/05/06 17:31

1.写一个类继承与FileFilter

[java] view plaincopy
  1. package com.dream.musicplayer;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileFilter;  
  5.   
  6. public class MP3FileFilter implements FileFilter {  
  7.   
  8.     @Override  
  9.     public boolean accept(File file) {  
  10.         // TODO Auto-generated method stub  
  11. //      return false;  
  12.           
  13.         if(file.isDirectory())  
  14.             return true;  
  15.         else  
  16.         {  
  17.             String name = file.getName();  
  18.             if(name.endsWith(".mp3") || name.endsWith(".mp4"))  
  19.                 return true;  
  20.             else  
  21.                 return false;  
  22.         }  
  23.           
  24.     }  
  25.   
  26. }  

 

2.传一个路径,获取改路径下的所有mp3 and mp4文件

[java] view plaincopy
  1. /** 
  2.      * get all the music file in the rootpath. 
  3.      * @param rootPath 
  4.      */  
  5.     public void getAllFilePath(String rootPath)  
  6.     {  
  7.           
  8.         File file = new File(rootPath);  
  9.         File[] files = file.listFiles(new MP3FileFilter());  
  10.         for(int i=0;i<files.length;i++)  
  11.         {  
  12.             if(files[i].isDirectory())  
  13.             {  
  14.                 getAllFilePath(files[i].getPath());  
  15.             }  
  16.             else  
  17.             {  
  18.                 mArrayListMusicPaths.add(files[i].getPath());  
  19.                 mArrayListMusicNames.add(files[i].getName());  
  20.                 System.out.println(files[i].getPath());  
  21.             }  
  22.         }  
  23.           
  24.               
  25.     }  

 

这样就可以获取某个路径下的所有需要获取的文件类型了。

0 0
原创粉丝点击