IO Exercise(Ⅰ)---------- 文件后缀名的过滤

来源:互联网 发布:openresty是什么软件 编辑:程序博客网 时间:2024/05/22 09:01
对指定目录中的所有(包含子目录)特定后缀名的文件的绝对路径写入到一个文本文件中。
1. 首先,明确思路:以.java后缀名为例,设计思路
①. 对指定文件递归,将每个文件都遍历出来。
②. 将遍历出来的文件过滤。
③. 将②中满足的文件用容器存储。
④. 将容器中存储的文件绝对路径写入到一个文件中。

2. 分析所使用的技术:
①. 递归算法。
②. 文件过滤。
③. 集合。
④. IO

3.编码实现:
①. 对指定目录进行递归,使用文件过滤器过滤遍历出来的文件,将满足条件的存放到容器中。
/** * 定义一个功能对指定的目录进行递归 *  * @param dir : 指定的目录 * @param filenameFilter : 文件过滤器 * @param list : 将符合条件的文件名保存的集合 */public static void listAllJavaFile(File dir, FilenameFilter filenameFilter,List<File> list) {// 遍历目录中的文件. File类的 public File[] listFiles()File[] files = dir.listFiles();if (files != null) {for (File file : files) {if (file.isDirectory()) { // 递归遍历listAllJavaFile(file, filenameFilter, list);} else {// 过滤特点后缀名的文件if (filenameFilter.accept(dir, file.getName())) {list.add(file);}}}}}
②. 容器中存储的内容写入到文件中。
/** * 集合中存储的内容写入到文件中 *  * @param files : 文件集合 * @param des : 用写入的目的地 * @throws IOException */public static void write2File(List<File> files, File des)throws IOException {BufferedWriter bufferedWriter = null;try {bufferedWriter = new BufferedWriter(new FileWriter(des));// 便利集合for (File file : files) {bufferedWriter.write(file.getAbsolutePath());bufferedWriter.newLine();bufferedWriter.flush();}} finally {if (bufferedWriter != null)try {bufferedWriter.close();} catch (Exception e) {throw new RuntimeException("关闭失败!");}}}
③. 自定义后缀名过滤器。
/** * 自定义文件过滤器 */public class MyFilenameFilter implements FilenameFilter {private String suffix;public MyFilenameFilter(String suffix) {this.suffix = suffix;}public boolean accept(File dir, String name) {return name.endsWith(suffix);}}
④. 测试。
public static void main(String[] args) throws IOException {File dir = new File("E:\\pegasus");MyFilenameFilter filter = new MyFilenameFilter(".java");List<File> list = new ArrayList<>();listAllJavaFile(dir, filter, list);File file = new File(dir, "java文件目录.txt");write2File(list, file);}

虽然以上文件过滤方法是很好了,但是我还知道一种方法,java NIO中的glob模式。
现在我给大家简要的解释下java NIO中的Glob模式:
①. 什么是Glob
在编程设计中,Glob是一种模式,他使用通配符来指定文件名。例如:*.java就是一个简单的Glob,他指定了所有扩展名为“.java”的文件。Glob模式中广泛使用了两个通配符“*”和“?”。其中星号表示“任意的字符或字符组成字符串”,而问号则表示“任意单个字符”。
②. Java NIO中的Glob
Java SE7的NIO库引用了Glob模式,它用于FileSystem类,在PathMatcher getPathMatcher(String syntaxAndPattern)方法中使用。Glob可以作为参数传递给PathMatcher。同样地,在Files类中也可以使用Glob来遍历整个目录。
③. 本例子使用Glob实现
Ⅰ.对目录下的文件匹配
/** * 打印一个目录下所有匹配glob规则的文件名称 */private static void match(String glob, String location) throws IOException {final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);Files.walkFileTree(Paths.get(location), new SimpleFileVisitor<Path>() {@Overridepublic FileVisitResult visitFile(Path path,BasicFileAttributes attrs) throws IOException {if (pathMatcher.matches(path)) {System.out.println(path);}return FileVisitResult.CONTINUE;}});}
Ⅱ.使用Junit单元测试
@Testpublic void test(){String glob = "glob:**.java";String path = "E:/pegasus";match(glob, path);}
成功的打印出了需要的文件,关于写入文件的操作,上面已解决。
若有什么错误,望不吝赐教(赶紧告诉我,我好改,改晚了耽误其他人)。






0 0