前言:
文件IO是程序设计语言的一个特点,本文将针对Java的File文件名过滤进行测试。
测试目录截图:
测试结果:
data.txt output-3.txt output-4.txt output-d.txt people-id.txt qqmusic_cn_seed.txt text-a20.txt --- finish ----
版本一:接口继承
package com.yeezhao.common.io.v1; import java.io.File; import java.io.FilenameFilter; import java.util.regex.Pattern; public class MyFilenameFilter implements FilenameFilter { final static String REGEX = ".*\.txt"; @Override public boolean accept(File dir, String name) { return Pattern.matches(REGEX, name); } }
package com.yeezhao.common.io.v1; import java.io.File; import java.util.Arrays; public class FilenameFilterV1 { public static void main(String[] args) throws Exception{ System.out.println("--- start ----"); File file = new File("c://test"); String[] list = file.list(new MyFilenameFilter()); Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); //忽略字符串大小写进行字典排序 for(String l:list){ System.out.println(l); } System.out.println("--- finish ----"); } }
版本二:内部类初始化内部对象属性
package com.yeezhao.common.io.v2; import java.io.File; import java.io.FilenameFilter; import java.util.Arrays; import java.util.regex.Pattern; public class FilenameFilterV2 { private static String REGEX =".*\.txt"; private static FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return Pattern.matches(REGEX, name); } }; public static void main(String[] args) throws Exception { File file = new File("c://test"); String[] list = file.list(filter); Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); //忽略字符串大小写进行字典排序 for (String l : list) { System.out.println(l); } System.out.println("--- finish ----"); } }
版本三:内部类直接调用方法
package com.yeezhao.common.io.v3; import java.io.File; import java.io.FilenameFilter; import java.util.Arrays; import java.util.regex.Pattern; public class FilenameFilterV3 { private static String REGEX =".*\.txt"; public static void main(String[] args) { File file = new File("c://test/"); String[] list = file.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return Pattern.matches(REGEX, name); } }); Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); //忽略字符串大小写进行字典排序 for (String l : list) { System.out.println(l); } System.out.println("--- finish ----"); } }
附:File对象的list()方法
后语:
Java.io涉及相当多的工具类,后续在研究之余希望能上手java.nio的一些内容并进行对比为是!