public class FileSelector {
public static File showOpenDlg(Component parent, String[] exts){
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileFilterImpl(exts));
chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
return chooser.getSelectedFile();
}
return null;
}
public static File showSaveDlg(Component parent, String[] exts, String displayName){
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileFilterImpl(exts));
chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
chooser.setSelectedFile(new File(displayName));
int returnVal = chooser.showSaveDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
return chooser.getSelectedFile();
}
return null;
}
}
public class FileFilterImpl extends FileFilter{
public String[] exts;
public FileFilterImpl(String[] exts){
this.exts = exts;
}
public boolean accept(File f)
{
if (f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if(extension == null)
return false;
for(int i=0; i < exts.length; i++){
if(extension.toLowerCase().equals(exts[i]))
return true;
}
return false;
}
public String getDescription(){
StringBuffer sb = new StringBuffer();
for(int i=0; i < exts.length; i++)
{
if(i == (exts.length-1))
sb.append(exts[i]);
else
sb.append(exts[i] + ", ");
}
return sb.toString()+" File Selection";
}
public String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i+1).toLowerCase();
}
return ext;
}
public String getTypeDescription(File f) {
String extension = getExtension(f);
String type = null;
if (extension != null) {
for(int i=0; i < exts.length; i++){
if(exts[i].toLowerCase().equals(extension))
return extension.toUpperCase() + " File";
}
}
return type;
}
}