java中文件过滤器,过滤任意类型的文件,下面以过滤.mp3和.lrc文件为例:
1、定义一个文件过滤器实现FileFilter 接口(MP3FileFilter.java)
package com.demo.file;
import java.io.File;
import java.io.FileFilter;
public class MP3FileFilter implements FileFilter {
/** 此过滤器是否接受给定的文件。 */
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
String name = file.getName();
if (name.endsWith(".lrc") || name.endsWith(".mp3")) {
return true;
} else {
return false;
}
}
}
}
2、文件过滤器的应用,测试(Test.java)
package com.demo.file;
import java.io.File;
public class Test {
public static void getAllFilePath(String rootPath) {
File file = new File(rootPath);
File[] files = file.listFiles(new MP3FileFilter());
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
getAllFilePath(files[i].getPath());
} else {
System.out.println(files[i].getName() + "<<---->>" + files[i].getPath());
}
}
}
/**
* 测试文件过滤器
*
* @author: kpchen
* @createTime: 2014年11月28日 上午9:11:23
* @history:
* @param args
* void
*/
public static void main(String[] args) {
String[] strs = { "C", "D", "E", "F" };
print(strs);
}
/**
* 遍历计算中各个盘中你想要搜索的文件
*
* @author: kpchen
* @createTime: 2014年11月28日 上午9:23:37
* @history:
* @param strs
* void
*/
private static void print(String[] strs) {
for (String path : strs) {
try {
getAllFilePath(path + ":\\");
} catch (Exception e) {
}
}
}
}