import java.io.File;

import javax.swing.filechooser.FileFilter;

public class ExtensionFilter extends FileFilter {
    private String extensions[];

    private String description;

    public ExtensionFilter(String description, String extension) {
        this(description, new String[] { extension });
    }

    public ExtensionFilter(String description, String extensions[]) {
        this.description = description;
        this.extensions = (String[]) extensions.clone();
    }

    public boolean accept(File file) {
        if (file.isDirectory()) {
            return true;
        }
        int count = extensions.length;
        String path = file.getAbsolutePath();
        for (int i = 0; i < count; i++) {
            String ext = extensions[i];
            if (path.endsWith(ext)
                    && (path.charAt(path.length() - ext.length()) == '.')) {
                return true;
            }
        }
        return false;
    }

    public String getDescription() {
        return (description == null ? extensions[0] : description);
    }
}

 

 

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

public class AdJFileChooser extends JFileChooser{
    private String extension;
    // set file type filter
    public AdJFileChooser(String extension) {
        FileFilter type1 = new ExtensionFilter("Microsoft Office Excel Files(.xls)", ".xls");
        addChoosableFileFilter(type1);
        this.extension= extension;
    }
    @Override
    public File getSelectedFile() {
        File file = super.getSelectedFile();
        if (file != null){
            Pattern pattern=Pattern.compile(".*\\.[a-z]+",Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(file.getAbsolutePath());
            if(!matcher.find()){
                file=new File(file.getAbsolutePath().concat(extension));
            }
        }
        return file;
    }
}