Filter, FilenameFilter用法和文件排序

Filter, FilenameFilter用法和文件排序
FileFilter和FilenameFilter这两个类的用法都很简单,都只有一个方法

FileFilter
/**
* @param pathname The abstract pathname to be tested
*/
boolean accept(File pathname)
用法示例:
import java.io.File;
import java.io.FileFilter;

public class Main {

public static void main(String[] args) {

File cwd = new File(System.getProperty("user.dir"));
File[] htmlFiles = cwd.listFiles(new HTMLFileFilter());
for (int i = 0; i < htmlFiles.length; i++) {
System.out.println(htmlFiles[i]);
}
}
}

class HTMLFileFilter implements FileFilter {

public boolean accept(File pathname) {

if (pathname.getName().endsWith(".html"))
return true;
if (pathname.getName().endsWith(".htm"))
return true;
return false;
}
}

FilenameFilter

/**
* @param dir - the directory in which the file was found.
* @param name - the name of the file.
*/
boolean accept(File dir, String name)

用法示例:
import java.io.File;
import java.io.FilenameFilter;

class ExtensionFilter implements FilenameFilter {
String ext;

public ExtensionFilter(String ext) {
this.ext = "." + ext;
}

public boolean accept(File dir, String name) {
return name.endsWith(ext);
}
}

public class Main {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
FilenameFilter only = new ExtensionFilter("html");
String s[] = f1.list(only);
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
}
}

文件排序
排序规则:目录排在前面,按字母顺序排序文件列表

List<File> files = Arrays.asList(new File("<目录>").listFiles());
Collections.sort(files, new Comparator<File>(){
@Override
public int compare(File o1, File o2) {
if(o1.isDirectory() && o2.isFile())
return -1;
if(o1.isFile() && o2.isDirectory())
return 1;
return o1.getName().compareTo(o2.getName());
}
});

for(File f : files)
System.out.println(f.getName());

from: www.hilyb.com
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值