文件过滤器 FileFilter

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

	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时间辜负了谁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值