Example: show only java files from d:/myprogram directory
import java.io.File;
import java.io.FilenameFilter;
public class FilesList{
public static void main(String[] args){
showFileNames("d:/myprogram","java");
}
public static void showFileNames(String src, String ext){
File f=new File(src); //create file object to connect to the source directory
if(!f.exists()){
System.out.println("Source directory does not exist.");
System.exit(-1);
}
String[] filenames;
if(!ext.equals("")){
filenames=f.list(new ExtFilter(ext)); //list files by extension
for(String name:filenames){
System.out.println(name);
}
}
}
}
class ExtFilter implements FilenameFilter{
String ext="";
public ExtFilter(String ext){
this.ext="."+ext;
}
public boolean accept(File f, String name){
if(name.endsWith(ext)) return true;
else return false;
}
}
import java.io.FilenameFilter;
public class FilesList{
public static void main(String[] args){
showFileNames("d:/myprogram","java");
}
public static void showFileNames(String src, String ext){
File f=new File(src); //create file object to connect to the source directory
if(!f.exists()){
System.out.println("Source directory does not exist.");
System.exit(-1);
}
String[] filenames;
if(!ext.equals("")){
filenames=f.list(new ExtFilter(ext)); //list files by extension
for(String name:filenames){
System.out.println(name);
}
}
}
}
class ExtFilter implements FilenameFilter{
String ext="";
public ExtFilter(String ext){
this.ext="."+ext;
}
public boolean accept(File f, String name){
if(name.endsWith(ext)) return true;
else return false;
}
}