Skip to content

Instantly share code, notes, and snippets.

@sprohaszka
Created August 25, 2010 17:30
Show Gist options
  • Save sprohaszka/549921 to your computer and use it in GitHub Desktop.
Save sprohaszka/549921 to your computer and use it in GitHub Desktop.
Extension file filter
import java.io.File;
import java.util.Vector;
/**
* Filter on the extension of the files.
* @author sprohaszka
*
*/
public class FileExtFilter extends javax.swing.filechooser.FileFilter {
private static final String SEPARATOR = ";";
private static final String EXT_SEPARATOR = ".";
private final String sFilterDescription = "Fichiers autorisés";
private Vector<String> _tExt = new Vector<String>();
/**
* Filter on the extension of the file.
* The parameter has to be like : ".doc;.jpg". No wildcards.
* @param sExtensions List of extensions on which the filter will applied
*/
public FileExtFilter(String sExtensions) {
String[] tExt = sExtensions.split(SEPARATOR);
for(String sExt : tExt) {
_tExt.add(sExt);
}
}
/**
* Filter on the extension of the file.
* The parameter has to be like : ".doc;.jpg". No wildcards.
* @param sExtensions List of extensions on which the filter will applied
* @param sDescription Name to display in the filechooser combobox
*/
public FileExtFilter(String sExtensions, String sDescription) {
String[] tExt = sExtensions.split(SEPARATOR);
for(String sExt : tExt) {
_tExt.add(sExt);
}
}
@Override
public boolean accept(File f) {
boolean bAcceted = false;
// If the file is a directory, we don't filter it (otherwise it's impossible to navigate).
if(f.isDirectory() == false) {
String sFileName = f.getName();
int iIdxExt = sFileName.lastIndexOf(EXT_SEPARATOR);
// If the file has no extension, we don't want to see it
if(iIdxExt > 0) {
String sExt = sFileName.substring(iIdxExt);
if(_tExt.contains(sExt) == true) {
bAcceted = true;
}
}
} else {
bAcceted = true;
}
return bAcceted;
}
@Override
public String getDescription() {
return sFilterDescription;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment