码迷,mamicode.com
首页 > 编程语言 > 详细

Java:搜索特定后缀名的文件

时间:2014-11-17 22:30:40      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   使用   sp   java   for   

写了个Java程序,以特定后缀名为条件,在指定目录内递归搜索文件,再生成文件列表。

 

 1 import java.io.File;
 2 import java.util.ArrayList;
 3 import java.util.List;
 4 
 5 public class FileListGenerator {
 6 
 7     // FileList类可寻找指定路径下所有指定文件后缀名的文件,并生成文件列表 - List<File>
 8 
 9     FileListGenerator(File path) { // 如果未指定文件后缀名
10         if (path.isDirectory() && path.isAbsolute()) {
11             this.entryPath = path;
12         } else {
13             throw new IllegalArgumentException("The given path is not absolute directory!!");
14         }
15         this.specifySuffix = false// 没有传入指定后缀名的参数,所以将specifySuffix设为false
16         fileList = new ArrayList<File>(); // 初始化文件列表
17     }
18 
19     FileListGenerator(File path, String fileNameSuffix) { // 如果指定了文件后缀名
20         if (path.isDirectory() && path.isAbsolute()) {
21             this.entryPath = path;
22         } else {
23             throw new IllegalArgumentException("The given path is not absolute directory!!");
24         }
25         this.specifySuffix = true;
26         this.fileNameSuffix = fileNameSuffix;
27         fileList = new ArrayList<File>(); // 初始化文件列表
28     }
29 
30     private File entryPath; // 搜索文件的入口路径
31     private List<File> fileList; // 对象类型为File的列表,该列表的初始化在构造方法中完成
32     private boolean specifySuffix; // 是否指定搜索目标文件的后缀名,以开启搜索特定文件功能
33     private String fileNameSuffix;
34 
35     public List<File> getFileList() {
36         this.fillFileList(entryPath);
37         return fileList;
38     }
39 
40     private void fillFileList(File absolutePath) {
41         // 寻找指定后缀名或者普通文件,并填充文件列表fileList
42         File[] fileListInDir = absolutePath.listFiles(); // ,用以保存指定路径下所有文件&目录列表,注意目录也是File类型
43 
44         if (this.specifySuffix) {
45             for (int i = 0; i < fileListInDir.length; i++) {
46                 if (fileListInDir[i].isFile()) { // 判断当前项是否是文件,或者是目录
47                     if (fileListInDir[i].getAbsolutePath().endsWith(this.fileNameSuffix)) {
48                         this.fileList.add(fileListInDir[i]);
49                     }
50                 } else {
51                     this.fillFileList(fileListInDir[i]); // 如果数组fileListInDir中的当前项不是文件,而是目录时,递归调用方法fillFileList()
52                 }
53             }
54         } else {
55             for (File x : fileListInDir) { // 如果不指定文件后缀名的话,寻找所有的文件的过程就简单了...
56                 if (x.isFile()) {
57                     this.fileList.add(x);
58                 } else {
59                     this.fillFileList(x);
60                 }
61             }
62         }
63 
64         fileListInDir = null// 此时该临时文件列表已完成使用
65     }

66 } 

 

Java:搜索特定后缀名的文件

标签:style   blog   io   color   ar   使用   sp   java   for   

原文地址:http://www.cnblogs.com/summer2012/p/4104465.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!