javaswingjfilechooser

JFileChooser to pick a directory or a single file


is it possible to make a JFileChooser which can choose a file or a directory? Because, if I use a filefilter in my chooser it is only possible to choose the files included the filter option, but I am no longer able to choose a directory.

this is my JFileChooser

JFileChooser ch = new JFileChooser();
  ch.setAcceptAllFileFilterUsed(false);
  ch.setFileFilter(new FileFilter() {

    public boolean accept(File f) {
      if (f != null && f.isDirectory()) {
        return true;
      }
      if (f == null || !f.getName().toUpperCase().endsWith(".PROPERTIES")) {
        return false;
      }
      return true;
    }

    public String getDescription() {
      return "Property Files" + " (*.properties)";
    }
  });
  ch.setCurrentDirectory(new File("."));
  ch.showOpenDialog(this);
  if (ch.getSelectedFile() != null) {
    ressource = ch.getSelectedFile();
  }
  else {
    return;
  }
  txtRessource.setText(ressource.getAbsolutePath());

Solution

  • Just call

    ch.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    

    And that way you will be able to select either a file or a directory. This works with combination of your filter.

    Btw you don't have to implement the file filter too, there is a FileNameExtensionFilter which does exactly what you want (it also accepts folders):

    ch.setFileFilter(new FileNameExtensionFilter("Properties file", "properties"));