|
|
|
Java读取File的问题
|
2005年09月06日 15:40
|
|
|
标签列表
|
|
请教一个问题: 我想要读取某一个路径下,文件最后修改的时间大于我给定的所有的文件. 比如是E:\file 我想要等到一部分的file,即是文件最后修改的时间大于我给定的 我目前的做法是: 查看所有的File,一一比对,得到我想要的File //read path Vector needReadFile = new Vector(); Date fileDate = new Date(); File[] files = new File(readFilePath).listFiles(); if (files == null) { continue; } for (int x = 0; x < files.length; x++) { File tempFile = files[x]; Date fileDate = new Date(tempFile. lastModified()); if (fileDate.compare(lastModifyDate) == 1 ) { needReadFile.add(readFilePath + File.separator + tempFile.getName()); } } //end for(int i = 0 ; i< files.length ; i++)
虽然这样做是可以达到,当我的File很多的时候,效率很差了 请问高人,有没有别的方法,我不用比对所有的File,就可以做到呢,或别方法来提高效率呢
Thanks!
|
|
|
|
|
|
Re: Java读取File的问题
|
2005年09月06日 18:40
|
|
|
用FileFilter File[] files = new File(readFilePath).listFiles(new FileFilter(){ public boolean accept(File pathname){ //.判断修改日期,符合条件返回true;否则false; }});
|
|
|
|
|
|
Re: Java读取File的问题
|
2005年09月06日 20:08
|
|
|
|
把Verctor 该成ArrayList 你还在使用Verctor ??
|
|
|
|
|
|
Re: Java读取File的问题
|
2005年09月06日 20:22
|
|
|
主要问题不是用了Vector,或ArrayList的问题
|
|
|
|
|
|
Re: Java读取File的问题
|
2005年09月06日 20:24
|
|
|
To wild fox : 我还是有点不明白,可否写详细一点呢 还有你能说说他的好处吗? Thanks~
|
|
|
|
|
|
Re: Java读取File的问题
|
2005年09月07日 11:33
|
|
|
看看listFiles()和listFiles(FileFilter filter) 的源代码
public File[] listFiles() { String[] ss = list(); if (ss == null) return null; int n = ss.length; File[] fs = new File[n]; for (int i = 0; i < n; i++) { fs = new File(this.path, ss); } return fs; }
public File[] listFiles(FileFilter filter) { String ss[] = list(); if (ss == null) return null; ArrayList v = new ArrayList(); for (int i = 0 ; i < ss.length ; i++) { File f = new File(this.path, ss); if ((filter == null) || filter.accept(f)) { v.add(f); } } return (File[])(v.toArray(new File[0])); }
采用第二个方法以后,只需要遍历一遍,而且代码更清晰, 采用第一个方法,你取得列表以后还需要遍历一遍过滤掉不符合条件的.
File[] files = new File(readFilePath).listFiles(new FileFilter(){ public boolean accept(File pathname){ //.判断修改日期,符合条件返回true;否则false;
}});
这里采用匿名类,实现一个FileFilter,你要修改过滤的逻辑,只需要修改accept()方法就是了,当然,你也可以专门写一个类比如
class FileModifyDateFilter implements FileFilter{ private Date baseDate = null; public FileModifyDateFilter(Date d) { baseDate = d; }
public boolean accept(File f) { if (baseDate == null) return true; if (f.lastModified() > baseDate.getTime()) return true;
return false; } }
|
|
|
|
|
|
Re: Java读取File的问题
|
2005年09月07日 12:10
|
|
|
|
|
|
|
|
|
Re: Java读取File的问题
|
2005年09月07日 22:01
|
|
|
|
|
|
|