A very simple Java code, written in a small util:
Package com.util;
Import Java.io.File;
Import Java.io.FileFilter;
Import java.util.List; public class Fileutil {/** * provide two default file filters/public static filefilter Default_jsp_filter = NE
W Jspfilefilter ();
public static FileFilter Default_txt_filter = new Txtfilefilter ();
/** * This method would get all the target files under a specific directory * @param targetDir * @param filter * @param resultfiles * @return/public static list<file> Filtertargetfiles (File targetDir, FileFilter fil
ter, list<file> resultfiles) {/** * listfiles:only List the files in the "current directory", not include
* The files in the sub directories.
* * file[] files = targetdir.listfiles (filter);
for (file file:files) {if (File.isdirectory ()) {filtertargetfiles (file, filter, resultfiles);
else {resultfiles.add (file);
} return resultfiles; private static class Jspfilefilter implements FileFilter{@Override public boolean accept (file file) {if (File.isdirectory ()) {return true;
String fileName = File.getname ();
Return Filename.matches ("(? i). +jsp$");
}} private static class Txtfilefilter implements FileFilter {@Override public boolean accept (file file) {
if (File.isdirectory ()) {return true;
String fileName = File.getname ();
Return Filename.matches ("(? i). +txt$");
}
}
}
Test code:
Package Com.salmon;
Import Java.io.File;
Import java.util.ArrayList;
Import java.util.List;
Import Com.util.FileUtil;
public class Testreadfiles {public
static void Main (string[] args) {
String Targetdirpath = "D:\\zzzztestdir";
file TargetDir = new File (targetdirpath);
list<file> allfiles = new arraylist<file> ();
Allfiles = Fileutil.filtertargetfiles (TargetDir, Fileutil.default_txt_filter, allfiles);
After get all of the files, do the specific logic for the target files
dothelogic (allfiles);
}
/**
* Get all of the files in the target directory, here we are could conduct any logic for the files
*
* @param f Ileslist
* *
private static void Dothelogic (List<file> fileslist) {for
(File file:fileslist) {
System.out.println (File.getpath ());}}