读取某个路径下的所有文件 public class Test { public static void main(String[] args) { try{ File file = new File("c:\\"); String[] list ; list = file.list(new DirFilter(".txt")); ---------------》改成.xml for(int i = 0;i<list.length;i++){ System.out.println(list[i]); } }catch(Exception e){} } }
class DirFilter implements FilenameFilter{ String afn; DirFilter(String afn){this.afn = afn;} public boolean accept(File dir,String name){ String f = new File(name).getName(); return f.indexOf(afn)==-1; } } //过滤某些文件要实现 FilenameFilter 类 如果是包含那么 是 !=-1 如果是不包含那么就是 ==-1
thanks 我最后用的方法: File dir = new File("directoryName");
String[] children = dir.list(); if (children == null) { // Either dir does not exist or is not a directory } else { for (int i=0; i<children.length; i++) { // Get filename of file or directory String filename = children[i]; } }
// It is also possible to filter the list of returned files. // This example does not return any files that start with `.'. FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return !name.startsWith("."); } }; children = dir.list(filter);
// The list of files can also be retrieved as File objects File[] files = dir.listFiles();
// This filter only returns directories FileFilter fileFilter = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; files = dir.listFiles(fileFilter);
public class Test
{
public static void main(String[] args) {
try{
File file = new File("c:\\");
String[] list ;
list = file.list(new DirFilter(".txt")); ---------------》改成.xml
for(int i = 0;i<list.length;i++){
System.out.println(list[i]);
}
}catch(Exception e){}
}
}
class DirFilter implements FilenameFilter{
String afn;
DirFilter(String afn){this.afn = afn;}
public boolean accept(File dir,String name){
String f = new File(name).getName();
return f.indexOf(afn)==-1;
}
}
//过滤某些文件要实现 FilenameFilter 类 如果是包含那么 是 !=-1 如果是不包含那么就是 ==-1
我最后用的方法: File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children[i];
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);