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;
}
}
I create a simple application that allows the user to select a file from the JFileChooser dialog. I want the dialog show on the image files such as jpg, bmp, gif, png, tiff. Is it possible in Java to filter the files in the JFileChooser dialog?
ReplyDeleteYes. It is possible in Java to filter file names in JFileChooser component by using the FileNameExtensionFilter class. Try the following code below.
DeleteJFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "gif","png","bmp");
chooser.setFileFilter(filter);