Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all file names in directory using JFileChooser?

I'm using this bit of code:

 fileBrowser() {
      String toReturn = null;
      JFileChooser Chooser = new JFileChooser();
      int choosen = Chooser.showOpenDialog(fileBrowser.this);
      if (choosen == JFileChooser.APPROVE_OPTION) {         
            System.out.println(Chooser.getCurrentDirectory().toString()+"\\"+Chooser.getSelectedFile().getName());
      }

  }

To get the selected file name and location, which is all working fine. I was wondering as an addition, is there also a way to get all the filenames in that directory as well? something like .getAllFiles() I've had a search around and can't find one?

Thanks in Advance.

like image 282
James MV Avatar asked Dec 01 '11 14:12

James MV


People also ask

How do I find my JFileChooser file name?

JFileChooser fc = new JFileChooser(); int returnVal = fc. showSaveDialog(frame); if (returnVal == JFileChooser. APPROVE_OPTION){ File file = fc. getSelectedFile(); if (file.


2 Answers

Sure, use

File[] filesInDirectory = chooser.getCurrentDirectory().listFiles();

Then you can iterate over that array:

for ( File file : filesInDirectory ) {
    System.out.println(file.getName());
}
like image 191
Mark Peters Avatar answered Oct 24 '22 22:10

Mark Peters


Well, there's File.list(). This will list all files by their name from the specified directory (i.e. File). But this will also return directory names. In order to circumvent that, use the other File.list(FilenameFilter filter) method that will enable you to filter out directories from the listing.

like image 24
mre Avatar answered Oct 24 '22 22:10

mre