《Thinking In Java》-目录列表器

比较简单,不过在正则表达式那块差点被骗了,备忘一下。。。

----------------------

package com.trs.bwl;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.regex.Pattern;

public class DirList {

	public static void main(String[] args) {
		File path = new File("d:/");
		String[] list;
		list = path.list(new DirFilter(".*\\.txt"));
		Arrays.sort(list);
		for(int i = 0; i < list.length; i++) {
			System.out.println(i + ": " + list[i]);
		}
	}
	
}

class DirFilter implements FilenameFilter {
	
	private Pattern pattern;
	
	public DirFilter(String reg) {
		pattern = Pattern.compile(reg);
	}
	
	public boolean accept(File dir, String name) {
		return pattern.matcher(new File(name).getName()).matches();
	}
	
}

 

你可能感兴趣的:(java,正则表达式)