javafilefilter

How to make FileFilter in Java?


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();
        }

Solution

  • Here you will find some working examples. This is also a good example of FileFilter used in JFileChooser.

    The basics are, you need to override FileFilter class and write your custom code in its accpet method. The accept method in above example is doing filtration based on file types:

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

    Or more simpler to use is FileNameFilter which has accept method with filename as argument, so you don't need to get it manually.