62,623
社区成员
发帖
与我相关
我的任务
分享
public class CollectionFileName {
private String serchPath = null;// 搜索路径
String fileAccord = null;// 搜索的文件名字
private int count = 0;// 计数器
private ArrayList<String> fileConvene = null;// 搜索后符合条件的文件集
// private String[] tempString = null;// 接收list()返回的数组
File path;// = new File(serchPath,getFileAccord());//最终路径
public CollectionFileName() {
serchPath = "ALL ABOUT JAVA";
File file = new File(File.separator);
path = new File(file, serchPath);
}
public CollectionFileName(String serchPath, String fileAccord) {
this.serchPath = serchPath;
setFileAccord(fileAccord);
}
// 文件累加器
public void count() {
count++;
}
// 将符合条件的文件名字符串保存到ArrayList对象fileConvene中
public void filterFile() {
serchPath = "D:\\"; //★★★ 1.这里用我本地的盘符
// serchPath = "ALL ABOUT JAVA";
File file = new File(File.separator);
path = new File(file, serchPath);
// (如果取消上面三行的注释,能编译通过~添加注释后,抛出空指针异常~~)
// (代码要求~~在Demo类中设置搜索的条件~查询并列出所需文件名~~)
String[] tempString;
tempString = getPath().list();//★★★ 2.这里暂时不用过滤器
// tempString = getPath().list(new FilenameFilter() {
// public boolean accept(File file, String name) {
// return name.indexOf(fileAccord) != -1;
// }
// });// filter);
for (int i = 0; i < tempString.length; i++) {
fileConvene.add(tempString[i]);
count();
}
}
public void printResult() {
Object[] o = fileConvene.toArray();
for (int i = 0; i < o.length; i++) {
System.out.println(o[i]);
}
}
// 搜索文件名设置
public void setFileAccord(String fileAccord) {
this.fileAccord = fileAccord;
}
// 返回搜索的文件名
public String getFileAccord() {
return fileAccord;
}
// get() and set()method
public ArrayList getFileConvene() {
return fileConvene;
}
// 返回搜索全路径
public File getPath() {
path = new File(getSerchPath(), getFileAccord());
return path;
}
// 设置搜索全路径
public void setPath(File path) {
this.path = path;
}
// 返回parent搜索路径
public String getSerchPath() {
return serchPath;
}
// 设置parent搜索路径
public void setSerchPath(String serchPath) {
this.serchPath = serchPath;
}
// 返回符合文件的个数
public int getCount() {
return count;
}
//过滤条件
public void setFileConvene(ArrayList<String> al) {
fileConvene = al;
}
}
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
ArrayList <String> al = new ArrayList <String> ();
// FilenameFilterDemo ffd = new FilenameFilterDemo();
CollectionFileName cfn = new CollectionFileName("D:\\","All ABOUT JAVA");
// CollectionFileName.FilenameFilterDemo ffd = cfn.new FilenameFilterDemo();
// cfn.setFilter(ffd);
cfn.setFileAccord("temp");//★★★ 3.这里指定我本地D盘下的temp文件夹
cfn.setFileConvene(al);
cfn.filterFile();
cfn.printResult();
System.out.println();
System.out.println("符合文件的总数为: " + cfn.getCount() + "个");
}
}
cfn.setFileAccord("a");//搜索条件设置
File[] files = new File("D:\\temp\\").listFiles();//以File数组的形式返回
for (File file : files) {
if (file.isFile()) {
// do file...
} else if (file.isDirectory()) {//如果是文件夹,需要将这个file重新进行file.listFiles();遍历,重复for循环这个过程
// do directory....
}
}