How to make FileFilter in Java?

Harry89pl picture Harry89pl · Apr 9, 2011 · Viewed 157.3k times · Source

How to make a filter for .txt files?

I wrote something like this but it has an error:

 private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        JFileChooser chooser = new JFileChooser();
        int retval = chooser.showOpenDialog(null);
        
        String yourpath = "E:\\Programy Java\\Projekt_SR1\\src\\project_sr1";
        File directory = new File(yourpath);
        String[] myFiles;
        FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File directory, String fileName) {
            return fileName.endsWith(".txt");
        }
        };
        myFiles = directory.list(filter);

        
        if(retval == JFileChooser.APPROVE_OPTION)
        {
            File myFile = chooser.getSelectedFile();
        }

Answer

Fsee picture Fsee · Apr 9, 2011

Try something like this...

String yourPath = "insert here your path..";
File directory = new File(yourPath);
String[] myFiles = directory.list(new FilenameFilter() {
    public boolean accept(File directory, String fileName) {
        return fileName.endsWith(".txt");
    }
});