To list files of a certain type, create an instance of the FileFilter
class and override it\'s accept method. Use that instance when calling
the list method of the File class.
import java.io.File;
import java.io.FilenameFilter;
public class FileUtil {
public void listFiles(String dir) {
File directory = new File(dir);
if (!directory.isDirectory()) {
System.out.println("No directory provided");
return;
}
//create a FilenameFilter and override its accept-method
FilenameFilter filefilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
//if the file extension is .txt return true, else false
return name.endsWith(".txt");
}
};
String[] filenames = directory.list(filefilter);
for (String name : filenames) {
System.out.println(name);
}
}
public static void main(String[] args) {
FileUtil fileutil = new FileUtil();
fileutil.listFiles("C:\\\\temp");
}
}
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment